home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Python / compile.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  74.6 KB  |  3,519 lines

  1. /* Compile an expression node to intermediate code */
  2.  
  3. /* XXX TO DO:
  4.    XXX add __doc__ attribute == co_doc to code object attributes?
  5.    XXX   (it's currently the first item of the co_const tuple)
  6.    XXX Generate simple jump for break/return outside 'try...finally'
  7.    XXX Allow 'continue' inside try-finally
  8.    XXX New opcode for loading the initial index for a for loop
  9.    XXX other JAR tricks?
  10. */
  11.  
  12. #ifndef NO_PRIVATE_NAME_MANGLING
  13. #define PRIVATE_NAME_MANGLING
  14. #endif
  15.  
  16. #include "Python.h"
  17.  
  18. #include "node.h"
  19. #include "token.h"
  20. #include "graminit.h"
  21. #include "compile.h"
  22. #include "opcode.h"
  23. #include "structmember.h"
  24.  
  25. #include <ctype.h>
  26. #include "protos/compile.h"
  27.  
  28. /* Three symbols from graminit.h are also defined in Python.h, with
  29.    Py_ prefixes to their names.  Python.h can't include graminit.h
  30.    (which defines too many confusing symbols), but we can check here
  31.    that they haven't changed (which is very unlikely, but possible). */
  32. #if Py_single_input != single_input
  33.   #error "single_input has changed -- update Py_single_input in Python.h"
  34. #endif
  35. #if Py_file_input != file_input
  36.   #error "file_input has changed -- update Py_file_input in Python.h"
  37. #endif
  38. #if Py_eval_input != eval_input
  39.   #error "eval_input has changed -- update Py_eval_input in Python.h"
  40. #endif
  41.  
  42. int Py_OptimizeFlag = 0;
  43.  
  44. #define OP_DELETE 0
  45. #define OP_ASSIGN 1
  46. #define OP_APPLY 2
  47.  
  48. #define OFF(x) offsetof(PyCodeObject, x)
  49.  
  50. static struct memberlist code_memberlist[] = {
  51.     {"co_argcount",    T_INT,        OFF(co_argcount),    READONLY},
  52.     {"co_nlocals",    T_INT,        OFF(co_nlocals),    READONLY},
  53.     {"co_stacksize",T_INT,        OFF(co_stacksize),    READONLY},
  54.     {"co_flags",    T_INT,        OFF(co_flags),        READONLY},
  55.     {"co_code",    T_OBJECT,    OFF(co_code),        READONLY},
  56.     {"co_consts",    T_OBJECT,    OFF(co_consts),        READONLY},
  57.     {"co_names",    T_OBJECT,    OFF(co_names),        READONLY},
  58.     {"co_varnames",    T_OBJECT,    OFF(co_varnames),    READONLY},
  59.     {"co_filename",    T_OBJECT,    OFF(co_filename),    READONLY},
  60.     {"co_name",    T_OBJECT,    OFF(co_name),        READONLY},
  61.     {"co_firstlineno", T_INT,    OFF(co_firstlineno),    READONLY},
  62.     {"co_lnotab",    T_OBJECT,    OFF(co_lnotab),        READONLY},
  63.     {NULL}    /* Sentinel */
  64. };
  65.  
  66. static PyObject *
  67. code_getattr(co, name)
  68.     PyCodeObject *co;
  69.     char *name;
  70. {
  71.     return PyMember_Get((char *)co, code_memberlist, name);
  72. }
  73.  
  74. static void
  75. code_dealloc(co)
  76.     PyCodeObject *co;
  77. {
  78.     Py_XDECREF(co->co_code);
  79.     Py_XDECREF(co->co_consts);
  80.     Py_XDECREF(co->co_names);
  81.     Py_XDECREF(co->co_varnames);
  82.     Py_XDECREF(co->co_filename);
  83.     Py_XDECREF(co->co_name);
  84.     Py_XDECREF(co->co_lnotab);
  85.     PyObject_DEL(co);
  86. }
  87.  
  88. static PyObject *
  89. code_repr(co)
  90.     PyCodeObject *co;
  91. {
  92.     char buf[500];
  93.     int lineno = -1;
  94.     char *filename = "???";
  95.     char *name = "???";
  96.  
  97.     if (co->co_firstlineno != 0)
  98.         lineno = co->co_firstlineno;
  99.     if (co->co_filename && PyString_Check(co->co_filename))
  100.         filename = PyString_AsString(co->co_filename);
  101.     if (co->co_name && PyString_Check(co->co_name))
  102.         name = PyString_AsString(co->co_name);
  103.     sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>",
  104.         name, (long)co, filename, lineno);
  105.     return PyString_FromString(buf);
  106. }
  107.  
  108. static int
  109. code_compare(co, cp)
  110.     PyCodeObject *co, *cp;
  111. {
  112.     int cmp;
  113.     cmp = PyObject_Compare(co->co_name, cp->co_name);
  114.     if (cmp) return cmp;
  115.     cmp = co->co_argcount - cp->co_argcount;
  116.     if (cmp) return cmp;
  117.     cmp = co->co_nlocals - cp->co_nlocals;
  118.     if (cmp) return cmp;
  119.     cmp = co->co_flags - cp->co_flags;
  120.     if (cmp) return cmp;
  121.     cmp = PyObject_Compare(co->co_code, cp->co_code);
  122.     if (cmp) return cmp;
  123.     cmp = PyObject_Compare(co->co_consts, cp->co_consts);
  124.     if (cmp) return cmp;
  125.     cmp = PyObject_Compare(co->co_names, cp->co_names);
  126.     if (cmp) return cmp;
  127.     cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
  128.     return cmp;
  129. }
  130.  
  131. static long
  132. code_hash(co)
  133.     PyCodeObject *co;
  134. {
  135.     long h, h0, h1, h2, h3, h4;
  136.     h0 = PyObject_Hash(co->co_name);
  137.     if (h0 == -1) return -1;
  138.     h1 = PyObject_Hash(co->co_code);
  139.     if (h1 == -1) return -1;
  140.     h2 = PyObject_Hash(co->co_consts);
  141.     if (h2 == -1) return -1;
  142.     h3 = PyObject_Hash(co->co_names);
  143.     if (h3 == -1) return -1;
  144.     h4 = PyObject_Hash(co->co_varnames);
  145.     if (h4 == -1) return -1;
  146.     h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^
  147.         co->co_argcount ^ co->co_nlocals ^ co->co_flags;
  148.     if (h == -1) h = -2;
  149.     return h;
  150. }
  151.  
  152. PyTypeObject PyCode_Type = {
  153.     PyObject_HEAD_INIT(&PyType_Type)
  154.     0,
  155.     "code",
  156.     sizeof(PyCodeObject),
  157.     0,
  158.     (destructor)code_dealloc, /*tp_dealloc*/
  159.     0,        /*tp_print*/
  160.     (getattrfunc)code_getattr, /*tp_getattr*/
  161.     0,        /*tp_setattr*/
  162.     (cmpfunc)code_compare, /*tp_compare*/
  163.     (reprfunc)code_repr, /*tp_repr*/
  164.     0,        /*tp_as_number*/
  165.     0,        /*tp_as_sequence*/
  166.     0,        /*tp_as_mapping*/
  167.     (hashfunc)code_hash, /*tp_hash*/
  168. };
  169.  
  170. #define NAME_CHARS \
  171.     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
  172.  
  173. PyCodeObject *
  174. PyCode_New(argcount, nlocals, stacksize, flags,
  175.           code, consts, names, varnames, filename, name,
  176.           firstlineno, lnotab)
  177.     int argcount;
  178.     int nlocals;
  179.     int stacksize;
  180.     int flags;
  181.     PyObject *code;
  182.     PyObject *consts;
  183.     PyObject *names;
  184.     PyObject *varnames;
  185.     PyObject *filename;
  186.     PyObject *name;
  187.     int firstlineno;
  188.     PyObject *lnotab;
  189. {
  190.     PyCodeObject *co;
  191.     int i;
  192.     PyBufferProcs *pb;
  193.     /* Check argument types */
  194.     if (argcount < 0 || nlocals < 0 ||
  195.         code == NULL ||
  196.         consts == NULL || !PyTuple_Check(consts) ||
  197.         names == NULL || !PyTuple_Check(names) ||
  198.         varnames == NULL || !PyTuple_Check(varnames) ||
  199.         name == NULL || !PyString_Check(name) ||
  200.         filename == NULL || !PyString_Check(filename) ||
  201.         lnotab == NULL || !PyString_Check(lnotab)) {
  202.         PyErr_BadInternalCall();
  203.         return NULL;
  204.     }
  205.     pb = code->ob_type->tp_as_buffer;
  206.     if (pb == NULL ||
  207.         pb->bf_getreadbuffer == NULL ||
  208.         pb->bf_getsegcount == NULL ||
  209.         (*pb->bf_getsegcount)(code, NULL) != 1)
  210.     {
  211.         PyErr_BadInternalCall();
  212.         return NULL;
  213.     }
  214.     /* Make sure names and varnames are all strings, & intern them */
  215.     for (i = PyTuple_Size(names); --i >= 0; ) {
  216.         PyObject *v = PyTuple_GetItem(names, i);
  217.         if (v == NULL || !PyString_Check(v)) {
  218.             PyErr_BadInternalCall();
  219.             return NULL;
  220.         }
  221.         PyString_InternInPlace(&PyTuple_GET_ITEM(names, i));
  222.     }
  223.     for (i = PyTuple_Size(varnames); --i >= 0; ) {
  224.         PyObject *v = PyTuple_GetItem(varnames, i);
  225.         if (v == NULL || !PyString_Check(v)) {
  226.             PyErr_BadInternalCall();
  227.             return NULL;
  228.         }
  229.         PyString_InternInPlace(&PyTuple_GET_ITEM(varnames, i));
  230.     }
  231.     /* Intern selected string constants */
  232.     for (i = PyTuple_Size(consts); --i >= 0; ) {
  233.         PyObject *v = PyTuple_GetItem(consts, i);
  234.         char *p;
  235.         if (!PyString_Check(v))
  236.             continue;
  237.         p = PyString_AsString(v);
  238.         if ((int)strspn(p, NAME_CHARS)
  239.             != PyString_Size(v))
  240.             continue;
  241.         PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
  242.     }
  243.     co = PyObject_NEW(PyCodeObject, &PyCode_Type);
  244.     if (co != NULL) {
  245.         co->co_argcount = argcount;
  246.         co->co_nlocals = nlocals;
  247.         co->co_stacksize = stacksize;
  248.         co->co_flags = flags;
  249.         Py_INCREF(code);
  250.         co->co_code = code;
  251.         Py_INCREF(consts);
  252.         co->co_consts = consts;
  253.         Py_INCREF(names);
  254.         co->co_names = names;
  255.         Py_INCREF(varnames);
  256.         co->co_varnames = varnames;
  257.         Py_INCREF(filename);
  258.         co->co_filename = filename;
  259.         Py_INCREF(name);
  260.         co->co_name = name;
  261.         co->co_firstlineno = firstlineno;
  262.         Py_INCREF(lnotab);
  263.         co->co_lnotab = lnotab;
  264.     }
  265.     return co;
  266. }
  267.  
  268.  
  269. /* Data structure used internally */
  270.  
  271. struct compiling {
  272.     PyObject *c_code;        /* string */
  273.     PyObject *c_consts;    /* list of objects */
  274.     PyObject *c_const_dict; /* inverse of c_consts */
  275.     PyObject *c_names;    /* list of strings (names) */
  276.     PyObject *c_name_dict;  /* inverse of c_names */
  277.     PyObject *c_globals;    /* dictionary (value=None) */
  278.     PyObject *c_locals;    /* dictionary (value=localID) */
  279.     PyObject *c_varnames;    /* list (inverse of c_locals) */
  280.     int c_nlocals;        /* index of next local */
  281.     int c_argcount;        /* number of top-level arguments */
  282.     int c_flags;        /* same as co_flags */
  283.     int c_nexti;        /* index into c_code */
  284.     int c_errors;        /* counts errors occurred */
  285.     int c_infunction;    /* set when compiling a function */
  286.     int c_interactive;    /* generating code for interactive command */
  287.     int c_loops;        /* counts nested loops */
  288.     int c_begin;        /* begin of current loop, for 'continue' */
  289.     int c_block[CO_MAXBLOCKS]; /* stack of block types */
  290.     int c_nblocks;        /* current block stack level */
  291.     char *c_filename;    /* filename of current node */
  292.     char *c_name;        /* name of object (e.g. function) */
  293.     int c_lineno;        /* Current line number */
  294.     int c_stacklevel;    /* Current stack level */
  295.     int c_maxstacklevel;    /* Maximum stack level */
  296.     int c_firstlineno;
  297.     PyObject *c_lnotab;    /* Table mapping address to line number */
  298.     int c_last_addr, c_last_line, c_lnotab_next;
  299. #ifdef PRIVATE_NAME_MANGLING
  300.     char *c_private;    /* for private name mangling */
  301. #endif
  302. };
  303.  
  304.  
  305. /* Error message including line number */
  306.  
  307. static void
  308. com_error(c, exc, msg)
  309.     struct compiling *c;
  310.     PyObject *exc;
  311.     char *msg;
  312. {
  313.     int n = strlen(msg);
  314.     PyObject *v;
  315.     char buffer[30];
  316.     char *s;
  317.     c->c_errors++;
  318.     if (c->c_lineno <= 1) {
  319.         /* Unknown line number or single interactive command */
  320.         PyErr_SetString(exc, msg);
  321.         return;
  322.     }
  323.     sprintf(buffer, " (line %d)", c->c_lineno);
  324.     v = PyString_FromStringAndSize((char *)NULL, n + strlen(buffer));
  325.     if (v == NULL)
  326.         return; /* MemoryError, too bad */
  327.     s = PyString_AS_STRING((PyStringObject *)v);
  328.     strcpy(s, msg);
  329.     strcat(s, buffer);
  330.     PyErr_SetObject(exc, v);
  331.     Py_DECREF(v);
  332. }
  333.  
  334.  
  335. /* Interface to the block stack */
  336.  
  337. static void
  338. block_push(c, type)
  339.     struct compiling *c;
  340.     int type;
  341. {
  342.     if (c->c_nblocks >= CO_MAXBLOCKS) {
  343.         com_error(c, PyExc_SystemError,
  344.               "too many statically nested blocks");
  345.     }
  346.     else {
  347.         c->c_block[c->c_nblocks++] = type;
  348.     }
  349. }
  350.  
  351. static void
  352. block_pop(c, type)
  353.     struct compiling *c;
  354.     int type;
  355. {
  356.     if (c->c_nblocks > 0)
  357.         c->c_nblocks--;
  358.     if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
  359.         com_error(c, PyExc_SystemError, "bad block pop");
  360.     }
  361. }
  362.  
  363.  
  364. /* Prototype forward declarations */
  365.  
  366. static int com_init Py_PROTO((struct compiling *, char *));
  367. static void com_free Py_PROTO((struct compiling *));
  368. static void com_push Py_PROTO((struct compiling *, int));
  369. static void com_pop Py_PROTO((struct compiling *, int));
  370. static void com_done Py_PROTO((struct compiling *));
  371. static void com_node Py_PROTO((struct compiling *, struct _node *));
  372. static void com_factor Py_PROTO((struct compiling *, struct _node *));
  373. static void com_addbyte Py_PROTO((struct compiling *, int));
  374. static void com_addint Py_PROTO((struct compiling *, int));
  375. static void com_addoparg Py_PROTO((struct compiling *, int, int));
  376. static void com_addfwref Py_PROTO((struct compiling *, int, int *));
  377. static void com_backpatch Py_PROTO((struct compiling *, int));
  378. static int com_add Py_PROTO((struct compiling *, PyObject *, PyObject *, PyObject *));
  379. static int com_addconst Py_PROTO((struct compiling *, PyObject *));
  380. static int com_addname Py_PROTO((struct compiling *, PyObject *));
  381. static void com_addopname Py_PROTO((struct compiling *, int, node *));
  382. static void com_list Py_PROTO((struct compiling *, node *, int));
  383. static int com_argdefs Py_PROTO((struct compiling *, node *));
  384. static int com_newlocal Py_PROTO((struct compiling *, char *));
  385. static PyCodeObject *icompile Py_PROTO((struct _node *, struct compiling *));
  386. static PyCodeObject *jcompile Py_PROTO((struct _node *, char *,
  387.                     struct compiling *));
  388. static PyObject *parsestrplus Py_PROTO((node *));
  389. static PyObject *parsestr Py_PROTO((char *));
  390.  
  391. static int
  392. com_init(c, filename)
  393.     struct compiling *c;
  394.     char *filename;
  395. {
  396.     memset((void *)c, '\0', sizeof(struct compiling));
  397.     if ((c->c_code = PyString_FromStringAndSize((char *)NULL,
  398.                             1000)) == NULL)
  399.         goto fail;
  400.     if ((c->c_consts = PyList_New(0)) == NULL)
  401.         goto fail;
  402.     if ((c->c_const_dict = PyDict_New()) == NULL)
  403.         goto fail;
  404.     if ((c->c_names = PyList_New(0)) == NULL)
  405.         goto fail;
  406.     if ((c->c_name_dict = PyDict_New()) == NULL)
  407.         goto fail;
  408.     if ((c->c_globals = PyDict_New()) == NULL)
  409.         goto fail;
  410.     if ((c->c_locals = PyDict_New()) == NULL)
  411.         goto fail;
  412.     if ((c->c_varnames = PyList_New(0)) == NULL)
  413.         goto fail;
  414.     if ((c->c_lnotab = PyString_FromStringAndSize((char *)NULL,
  415.                               1000)) == NULL)
  416.         goto fail;
  417.     c->c_nlocals = 0;
  418.     c->c_argcount = 0;
  419.     c->c_flags = 0;
  420.     c->c_nexti = 0;
  421.     c->c_errors = 0;
  422.     c->c_infunction = 0;
  423.     c->c_interactive = 0;
  424.     c->c_loops = 0;
  425.     c->c_begin = 0;
  426.     c->c_nblocks = 0;
  427.     c->c_filename = filename;
  428.     c->c_name = "?";
  429.     c->c_lineno = 0;
  430.     c->c_stacklevel = 0;
  431.     c->c_maxstacklevel = 0;
  432.     c->c_firstlineno = 0;
  433.     c->c_last_addr = 0;
  434.     c->c_last_line = 0;
  435.     c-> c_lnotab_next = 0;
  436.     return 1;
  437.     
  438.   fail:
  439.     com_free(c);
  440.      return 0;
  441. }
  442.  
  443. static void
  444. com_free(c)
  445.     struct compiling *c;
  446. {
  447.     Py_XDECREF(c->c_code);
  448.     Py_XDECREF(c->c_consts);
  449.     Py_XDECREF(c->c_const_dict);
  450.     Py_XDECREF(c->c_names);
  451.     Py_XDECREF(c->c_name_dict);
  452.     Py_XDECREF(c->c_globals);
  453.     Py_XDECREF(c->c_locals);
  454.     Py_XDECREF(c->c_varnames);
  455.     Py_XDECREF(c->c_lnotab);
  456. }
  457.  
  458. static void
  459. com_push(c, n)
  460.     struct compiling *c;
  461.     int n;
  462. {
  463.     c->c_stacklevel += n;
  464.     if (c->c_stacklevel > c->c_maxstacklevel)
  465.         c->c_maxstacklevel = c->c_stacklevel;
  466. }
  467.  
  468. static void
  469. com_pop(c, n)
  470.     struct compiling *c;
  471.     int n;
  472. {
  473.     if (c->c_stacklevel < n) {
  474.         /* fprintf(stderr,
  475.             "%s:%d: underflow! nexti=%d, level=%d, n=%d\n",
  476.             c->c_filename, c->c_lineno,
  477.             c->c_nexti, c->c_stacklevel, n); */
  478.         c->c_stacklevel = 0;
  479.     }
  480.     else
  481.         c->c_stacklevel -= n;
  482. }
  483.  
  484. static void
  485. com_done(c)
  486.     struct compiling *c;
  487. {
  488.     if (c->c_code != NULL)
  489.         _PyString_Resize(&c->c_code, c->c_nexti);
  490.     if (c->c_lnotab != NULL)
  491.         _PyString_Resize(&c->c_lnotab, c->c_lnotab_next);
  492. }
  493.  
  494. static void
  495. com_addbyte(c, byte)
  496.     struct compiling *c;
  497.     int byte;
  498. {
  499.     int len;
  500.     /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
  501.     if (byte < 0 || byte > 255) {
  502.         /*
  503.         fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
  504.         fatal("com_addbyte: byte out of range");
  505.         */
  506.         com_error(c, PyExc_SystemError,
  507.               "com_addbyte: byte out of range");
  508.     }
  509.     if (c->c_code == NULL)
  510.         return;
  511.     len = PyString_Size(c->c_code);
  512.     if (c->c_nexti >= len) {
  513.         if (_PyString_Resize(&c->c_code, len+1000) != 0) {
  514.             c->c_errors++;
  515.             return;
  516.         }
  517.     }
  518.     PyString_AsString(c->c_code)[c->c_nexti++] = byte;
  519. }
  520.  
  521. static void
  522. com_addint(c, x)
  523.     struct compiling *c;
  524.     int x;
  525. {
  526.     com_addbyte(c, x & 0xff);
  527.     com_addbyte(c, x >> 8); /* XXX x should be positive */
  528. }
  529.  
  530. static void
  531. com_add_lnotab(c, addr, line)
  532.     struct compiling *c;
  533.     int addr;
  534.     int line;
  535. {
  536.     int size;
  537.     char *p;
  538.     if (c->c_lnotab == NULL)
  539.         return;
  540.     size = PyString_Size(c->c_lnotab);
  541.     if (c->c_lnotab_next+2 > size) {
  542.         if (_PyString_Resize(&c->c_lnotab, size + 1000) < 0) {
  543.             c->c_errors++;
  544.             return;
  545.         }
  546.     }
  547.     p = PyString_AsString(c->c_lnotab) + c->c_lnotab_next;
  548.     *p++ = addr;
  549.     *p++ = line;
  550.     c->c_lnotab_next += 2;
  551. }
  552.  
  553. static void
  554. com_set_lineno(c, lineno)
  555.     struct compiling *c;
  556.     int lineno;
  557. {
  558.     c->c_lineno = lineno;
  559.     if (c->c_firstlineno == 0) {
  560.         c->c_firstlineno = c->c_last_line = lineno;
  561.     }
  562.     else {
  563.         int incr_addr = c->c_nexti - c->c_last_addr;
  564.         int incr_line = lineno - c->c_last_line;
  565.         while (incr_addr > 0 || incr_line > 0) {
  566.             int trunc_addr = incr_addr;
  567.             int trunc_line = incr_line;
  568.             if (trunc_addr > 255)
  569.                 trunc_addr = 255;
  570.             if (trunc_line > 255)
  571.                 trunc_line = 255;
  572.             com_add_lnotab(c, trunc_addr, trunc_line);
  573.             incr_addr -= trunc_addr;
  574.             incr_line -= trunc_line;
  575.         }
  576.         c->c_last_addr = c->c_nexti;
  577.         c->c_last_line = lineno;
  578.     }
  579. }
  580.  
  581. static void
  582. com_addoparg(c, op, arg)
  583.     struct compiling *c;
  584.     int op;
  585.     int arg;
  586. {
  587.     if (op == SET_LINENO) {
  588.         com_set_lineno(c, arg);
  589.         if (Py_OptimizeFlag)
  590.             return;
  591.     }
  592.     com_addbyte(c, op);
  593.     com_addint(c, arg);
  594. }
  595.  
  596. static void
  597. com_addfwref(c, op, p_anchor)
  598.     struct compiling *c;
  599.     int op;
  600.     int *p_anchor;
  601. {
  602.     /* Compile a forward reference for backpatching */
  603.     int here;
  604.     int anchor;
  605.     com_addbyte(c, op);
  606.     here = c->c_nexti;
  607.     anchor = *p_anchor;
  608.     *p_anchor = here;
  609.     com_addint(c, anchor == 0 ? 0 : here - anchor);
  610. }
  611.  
  612. static void
  613. com_backpatch(c, anchor)
  614.     struct compiling *c;
  615.     int anchor; /* Must be nonzero */
  616. {
  617.     unsigned char *code = (unsigned char *) PyString_AsString(c->c_code);
  618.     int target = c->c_nexti;
  619.     int dist;
  620.     int prev;
  621.     for (;;) {
  622.         /* Make the JUMP instruction at anchor point to target */
  623.         prev = code[anchor] + (code[anchor+1] << 8);
  624.         dist = target - (anchor+2);
  625.         code[anchor] = dist & 0xff;
  626.         code[anchor+1] = dist >> 8;
  627.         if (!prev)
  628.             break;
  629.         anchor -= prev;
  630.     }
  631. }
  632.  
  633. /* Handle literals and names uniformly */
  634.  
  635. static int
  636. com_add(c, list, dict, v)
  637.     struct compiling *c;
  638.     PyObject *list;
  639.     PyObject *dict;
  640.     PyObject *v;
  641. {
  642.     PyObject *w, *t, *np=NULL;
  643.     long n;
  644.  
  645.     t = Py_BuildValue("(OO)", v, v->ob_type);
  646.     if (t == NULL)
  647.         goto fail;
  648.     w = PyDict_GetItem(dict, t);
  649.     if (w != NULL) {
  650.         n = PyInt_AsLong(w);
  651.     } else {
  652.         n = PyList_Size(list);
  653.         np = PyInt_FromLong(n);
  654.         if (np == NULL)
  655.             goto fail;
  656.         if (PyList_Append(list, v) != 0)
  657.             goto fail;
  658.         if (PyDict_SetItem(dict, t, np) != 0)
  659.             goto fail;
  660.         Py_DECREF(np);
  661.     }
  662.     Py_DECREF(t);
  663.     return n;
  664.   fail:
  665.     Py_XDECREF(np);
  666.     Py_XDECREF(t);
  667.     c->c_errors++;
  668.     return 0;
  669. }
  670.  
  671. static int
  672. com_addconst(c, v)
  673.     struct compiling *c;
  674.     PyObject *v;
  675. {
  676.     return com_add(c, c->c_consts, c->c_const_dict, v);
  677. }
  678.  
  679. static int
  680. com_addname(c, v)
  681.     struct compiling *c;
  682.     PyObject *v;
  683. {
  684.     return com_add(c, c->c_names, c->c_name_dict, v);
  685. }
  686.  
  687. #ifdef PRIVATE_NAME_MANGLING
  688. static int
  689. com_mangle(c, name, buffer, maxlen)
  690.     struct compiling *c;
  691.     char *name;
  692.     char *buffer;
  693.     int maxlen;
  694. {
  695.     /* Name mangling: __private becomes _classname__private.
  696.        This is independent from how the name is used. */
  697.     char *p;
  698.     int nlen, plen;
  699.     nlen = strlen(name);
  700.     if (nlen+2 >= maxlen)
  701.         return 0; /* Don't mangle __extremely_long_names */
  702.     if (name[nlen-1] == '_' && name[nlen-2] == '_')
  703.         return 0; /* Don't mangle __whatever__ */
  704.     p = c->c_private;
  705.     /* Strip leading underscores from class name */
  706.     while (*p == '_')
  707.         p++;
  708.     if (*p == '\0')
  709.         return 0; /* Don't mangle if class is just underscores */
  710.     plen = strlen(p);
  711.     if (plen + nlen >= maxlen)
  712.         plen = maxlen-nlen-2; /* Truncate class name if too long */
  713.     /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
  714.     buffer[0] = '_';
  715.     strncpy(buffer+1, p, plen);
  716.     strcpy(buffer+1+plen, name);
  717.     /* fprintf(stderr, "mangle %s -> %s\n", name, buffer); */
  718.     return 1;
  719. }
  720. #endif
  721.  
  722. static void
  723. com_addopnamestr(c, op, name)
  724.     struct compiling *c;
  725.     int op;
  726.     char *name;
  727. {
  728.     PyObject *v;
  729.     int i;
  730. #ifdef PRIVATE_NAME_MANGLING
  731.     char buffer[256];
  732.     if (name != NULL && name[0] == '_' && name[1] == '_' &&
  733.         c->c_private != NULL &&
  734.         com_mangle(c, name, buffer, (int)sizeof(buffer)))
  735.         name = buffer;
  736. #endif
  737.     if (name == NULL || (v = PyString_InternFromString(name)) == NULL) {
  738.         c->c_errors++;
  739.         i = 255;
  740.     }
  741.     else {
  742.         i = com_addname(c, v);
  743.         Py_DECREF(v);
  744.     }
  745.     /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
  746.     switch (op) {
  747.     case LOAD_NAME:
  748.     case STORE_NAME:
  749.     case DELETE_NAME:
  750.         if (PyDict_GetItemString(c->c_globals, name) != NULL) {
  751.             switch (op) {
  752.             case LOAD_NAME:   op = LOAD_GLOBAL;   break;
  753.             case STORE_NAME:  op = STORE_GLOBAL;  break;
  754.             case DELETE_NAME: op = DELETE_GLOBAL; break;
  755.             }
  756.         }
  757.     }
  758.     com_addoparg(c, op, i);
  759. }
  760.  
  761. static void
  762. com_addopname(c, op, n)
  763.     struct compiling *c;
  764.     int op;
  765.     node *n;
  766. {
  767.     char *name;
  768.     char buffer[1000];
  769.     /* XXX it is possible to write this code without the 1000
  770.        chars on the total length of dotted names, I just can't be
  771.        bothered right now */
  772.     if (TYPE(n) == STAR)
  773.         name = "*";
  774.     else if (TYPE(n) == dotted_name) {
  775.         char *p = buffer;
  776.         int i;
  777.         name = buffer;
  778.         for (i = 0; i < NCH(n); i += 2) {
  779.             char *s = STR(CHILD(n, i));
  780.             if (p + strlen(s) > buffer + (sizeof buffer) - 2) {
  781.                 com_error(c, PyExc_MemoryError,
  782.                       "dotted_name too long");
  783.                 name = NULL;
  784.                 break;
  785.             }
  786.             if (p != buffer)
  787.                 *p++ = '.';
  788.             strcpy(p, s);
  789.             p = strchr(p, '\0');
  790.         }
  791.     }
  792.     else {
  793.         REQ(n, NAME);
  794.         name = STR(n);
  795.     }
  796.     com_addopnamestr(c, op, name);
  797. }
  798.  
  799. static PyObject *
  800. parsenumber(co, s)
  801.     struct compiling *co;
  802.     char *s;
  803. {
  804.     extern double atof Py_PROTO((const char *));
  805.     char *end;
  806.     long x;
  807.     double dx;
  808. #ifndef WITHOUT_COMPLEX
  809.     Py_complex c;
  810.     int imflag;
  811. #endif
  812.  
  813.     errno = 0;
  814.     end = s + strlen(s) - 1;
  815. #ifndef WITHOUT_COMPLEX
  816.     imflag = *end == 'j' || *end == 'J';
  817. #endif
  818.     if (*end == 'l' || *end == 'L')
  819.         return PyLong_FromString(s, (char **)0, 0);
  820.     if (s[0] == '0')
  821.         x = (long) PyOS_strtoul(s, &end, 0);
  822.     else
  823.         x = PyOS_strtol(s, &end, 0);
  824.     if (*end == '\0') {
  825.         if (errno != 0) {
  826.             com_error(co, PyExc_OverflowError,
  827.                   "integer literal too large");
  828.             return NULL;
  829.         }
  830.         return PyInt_FromLong(x);
  831.     }
  832.     /* XXX Huge floats may silently fail */
  833. #ifndef WITHOUT_COMPLEX
  834.     if (imflag) {
  835.         c.real = 0.;
  836.         PyFPE_START_PROTECT("atof", return 0)
  837.         c.imag = atof(s);
  838.         PyFPE_END_PROTECT(c)
  839.         return PyComplex_FromCComplex(c);
  840.     }
  841.     else
  842. #endif
  843.     {
  844.         PyFPE_START_PROTECT("atof", return 0)
  845.         dx = atof(s);
  846.         PyFPE_END_PROTECT(dx)
  847.         return PyFloat_FromDouble(dx);
  848.     }
  849. }
  850.  
  851. static PyObject *
  852. parsestr(s)
  853.     char *s;
  854. {
  855.     PyObject *v;
  856.     int len;
  857.     char *buf;
  858.     char *p;
  859.     char *end;
  860.     int c;
  861.     int first = *s;
  862.     int quote = first;
  863.     int rawmode = 0;
  864.     int unicode = 0;
  865.     if (isalpha(quote) || quote == '_') {
  866.         if (quote == 'u' || quote == 'U') {
  867.             quote = *++s;
  868.             unicode = 1;
  869.         }
  870.         if (quote == 'r' || quote == 'R') {
  871.             quote = *++s;
  872.             rawmode = 1;
  873.         }
  874.     }
  875.     if (quote != '\'' && quote != '\"') {
  876.         PyErr_BadInternalCall();
  877.         return NULL;
  878.     }
  879.     s++;
  880.     len = strlen(s);
  881.     if (s[--len] != quote) {
  882.         PyErr_BadInternalCall();
  883.         return NULL;
  884.     }
  885.     if (len >= 4 && s[0] == quote && s[1] == quote) {
  886.         s += 2;
  887.         len -= 2;
  888.         if (s[--len] != quote || s[--len] != quote) {
  889.             PyErr_BadInternalCall();
  890.             return NULL;
  891.         }
  892.     }
  893.     if (unicode || Py_UnicodeFlag) {
  894.         if (rawmode)
  895.             return PyUnicode_DecodeRawUnicodeEscape(
  896.                 s, len, NULL);
  897.         else
  898.             return PyUnicode_DecodeUnicodeEscape(
  899.                 s, len, NULL);
  900.     }
  901.     else if (rawmode || strchr(s, '\\') == NULL) {
  902.         return PyString_FromStringAndSize(s, len);
  903.     }
  904.     v = PyString_FromStringAndSize((char *)NULL, len);
  905.     p = buf = PyString_AsString(v);
  906.     end = s + len;
  907.     while (s < end) {
  908.         if (*s != '\\') {
  909.             *p++ = *s++;
  910.             continue;
  911.         }
  912.         s++;
  913.         switch (*s++) {
  914.         /* XXX This assumes ASCII! */
  915.         case '\n': break;
  916.         case '\\': *p++ = '\\'; break;
  917.         case '\'': *p++ = '\''; break;
  918.         case '\"': *p++ = '\"'; break;
  919.         case 'b': *p++ = '\b'; break;
  920.         case 'f': *p++ = '\014'; break; /* FF */
  921.         case 't': *p++ = '\t'; break;
  922.         case 'n': *p++ = '\n'; break;
  923.         case 'r': *p++ = '\r'; break;
  924.         case 'v': *p++ = '\013'; break; /* VT */
  925.         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  926.         case '0': case '1': case '2': case '3':
  927.         case '4': case '5': case '6': case '7':
  928.             c = s[-1] - '0';
  929.             if ('0' <= *s && *s <= '7') {
  930.                 c = (c<<3) + *s++ - '0';
  931.                 if ('0' <= *s && *s <= '7')
  932.                     c = (c<<3) + *s++ - '0';
  933.             }
  934.             *p++ = c;
  935.             break;
  936.         case 'x':
  937.             if (isxdigit(Py_CHARMASK(*s))) {
  938.                 unsigned int x = 0;
  939.                 do {
  940.                     c = Py_CHARMASK(*s);
  941.                     s++;
  942.                     x = (x<<4) & ~0xF;
  943.                     if (isdigit(c))
  944.                         x += c - '0';
  945.                     else if (islower(c))
  946.                         x += 10 + c - 'a';
  947.                     else
  948.                         x += 10 + c - 'A';
  949.                 } while (isxdigit(Py_CHARMASK(*s)));
  950.                 *p++ = x;
  951.                 break;
  952.             }
  953.         /* FALLTHROUGH */
  954.         default: *p++ = '\\'; *p++ = s[-1]; break;
  955.         }
  956.     }
  957.     _PyString_Resize(&v, (int)(p - buf));
  958.     return v;
  959. }
  960.  
  961. static PyObject *
  962. parsestrplus(n)
  963.     node *n;
  964. {
  965.     PyObject *v;
  966.     int i;
  967.     REQ(CHILD(n, 0), STRING);
  968.     if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) {
  969.         /* String literal concatenation */
  970.         for (i = 1; i < NCH(n); i++) {
  971.             PyObject *s;
  972.             s = parsestr(STR(CHILD(n, i)));
  973.             if (s == NULL)
  974.             goto onError;
  975.             if (PyString_Check(v) && PyString_Check(s)) {
  976.             PyString_ConcatAndDel(&v, s);
  977.             if (v == NULL)
  978.                 goto onError;
  979.             }
  980.             else {
  981.             PyObject *temp;
  982.             temp = PyUnicode_Concat(v, s);
  983.             Py_DECREF(s);
  984.             if (temp == NULL)
  985.                 goto onError;
  986.             Py_DECREF(v);
  987.             v = temp;
  988.             }
  989.         }
  990.     }
  991.     return v;
  992.  
  993.  onError:
  994.     Py_XDECREF(v);
  995.     return NULL;
  996. }
  997.  
  998. static void
  999. com_list_constructor(c, n)
  1000.     struct compiling *c;
  1001.     node *n;
  1002. {
  1003.     int len;
  1004.     int i;
  1005.     if (TYPE(n) != testlist)
  1006.         REQ(n, exprlist);
  1007.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1008.     len = (NCH(n) + 1) / 2;
  1009.     for (i = 0; i < NCH(n); i += 2)
  1010.         com_node(c, CHILD(n, i));
  1011.     com_addoparg(c, BUILD_LIST, len);
  1012.     com_pop(c, len-1);
  1013. }
  1014.  
  1015. static void
  1016. com_dictmaker(c, n)
  1017.     struct compiling *c;
  1018.     node *n;
  1019. {
  1020.     int i;
  1021.     /* dictmaker: test ':' test (',' test ':' value)* [','] */
  1022.     for (i = 0; i+2 < NCH(n); i += 4) {
  1023.         /* We must arrange things just right for STORE_SUBSCR.
  1024.            It wants the stack to look like (value) (dict) (key) */
  1025.         com_addbyte(c, DUP_TOP);
  1026.         com_push(c, 1);
  1027.         com_node(c, CHILD(n, i+2)); /* value */
  1028.         com_addbyte(c, ROT_TWO);
  1029.         com_node(c, CHILD(n, i)); /* key */
  1030.         com_addbyte(c, STORE_SUBSCR);
  1031.         com_pop(c, 3);
  1032.     }
  1033. }
  1034.  
  1035. static void
  1036. com_atom(c, n)
  1037.     struct compiling *c;
  1038.     node *n;
  1039. {
  1040.     node *ch;
  1041.     PyObject *v;
  1042.     int i;
  1043.     REQ(n, atom);
  1044.     ch = CHILD(n, 0);
  1045.     switch (TYPE(ch)) {
  1046.     case LPAR:
  1047.         if (TYPE(CHILD(n, 1)) == RPAR) {
  1048.             com_addoparg(c, BUILD_TUPLE, 0);
  1049.             com_push(c, 1);
  1050.         }
  1051.         else
  1052.             com_node(c, CHILD(n, 1));
  1053.         break;
  1054.     case LSQB:
  1055.         if (TYPE(CHILD(n, 1)) == RSQB) {
  1056.             com_addoparg(c, BUILD_LIST, 0);
  1057.             com_push(c, 1);
  1058.         }
  1059.         else
  1060.             com_list_constructor(c, CHILD(n, 1));
  1061.         break;
  1062.     case LBRACE: /* '{' [dictmaker] '}' */
  1063.         com_addoparg(c, BUILD_MAP, 0);
  1064.         com_push(c, 1);
  1065.         if (TYPE(CHILD(n, 1)) != RBRACE)
  1066.             com_dictmaker(c, CHILD(n, 1));
  1067.         break;
  1068.     case BACKQUOTE:
  1069.         com_node(c, CHILD(n, 1));
  1070.         com_addbyte(c, UNARY_CONVERT);
  1071.         break;
  1072.     case NUMBER:
  1073.         if ((v = parsenumber(c, STR(ch))) == NULL) {
  1074.             i = 255;
  1075.         }
  1076.         else {
  1077.             i = com_addconst(c, v);
  1078.             Py_DECREF(v);
  1079.         }
  1080.         com_addoparg(c, LOAD_CONST, i);
  1081.         com_push(c, 1);
  1082.         break;
  1083.     case STRING:
  1084.         v = parsestrplus(n);
  1085.         if (v == NULL) {
  1086.             c->c_errors++;
  1087.             i = 255;
  1088.         }
  1089.         else {
  1090.             i = com_addconst(c, v);
  1091.             Py_DECREF(v);
  1092.         }
  1093.         com_addoparg(c, LOAD_CONST, i);
  1094.         com_push(c, 1);
  1095.         break;
  1096.     case NAME:
  1097.         com_addopname(c, LOAD_NAME, ch);
  1098.         com_push(c, 1);
  1099.         break;
  1100.     default:
  1101.         /* XXX fprintf(stderr, "node type %d\n", TYPE(ch)); */
  1102.         com_error(c, PyExc_SystemError,
  1103.               "com_atom: unexpected node type");
  1104.     }
  1105. }
  1106.  
  1107. static void
  1108. com_slice(c, n, op)
  1109.     struct compiling *c;
  1110.     node *n;
  1111.     int op;
  1112. {
  1113.     if (NCH(n) == 1) {
  1114.         com_addbyte(c, op);
  1115.     }
  1116.     else if (NCH(n) == 2) {
  1117.         if (TYPE(CHILD(n, 0)) != COLON) {
  1118.             com_node(c, CHILD(n, 0));
  1119.             com_addbyte(c, op+1);
  1120.         }
  1121.         else {
  1122.             com_node(c, CHILD(n, 1));
  1123.             com_addbyte(c, op+2);
  1124.         }
  1125.         com_pop(c, 1);
  1126.     }
  1127.     else {
  1128.         com_node(c, CHILD(n, 0));
  1129.         com_node(c, CHILD(n, 2));
  1130.         com_addbyte(c, op+3);
  1131.         com_pop(c, 2);
  1132.     }
  1133. }
  1134.  
  1135. static void
  1136. com_argument(c, n, pkeywords)
  1137.     struct compiling *c;
  1138.     node *n; /* argument */
  1139.     PyObject **pkeywords;
  1140. {
  1141.     node *m;
  1142.     REQ(n, argument); /* [test '='] test; really [keyword '='] test */
  1143.     if (NCH(n) == 1) {
  1144.         if (*pkeywords != NULL) {
  1145.             com_error(c, PyExc_SyntaxError,
  1146.                    "non-keyword arg after keyword arg");
  1147.         }
  1148.         else {
  1149.             com_node(c, CHILD(n, 0));
  1150.         }
  1151.         return;
  1152.     }
  1153.     m = n;
  1154.     do {
  1155.         m = CHILD(m, 0);
  1156.     } while (NCH(m) == 1);
  1157.     if (TYPE(m) != NAME) {
  1158.         com_error(c, PyExc_SyntaxError,
  1159.               "keyword can't be an expression");
  1160.     }
  1161.     else {
  1162.         PyObject *v = PyString_InternFromString(STR(m));
  1163.         if (v != NULL && *pkeywords == NULL)
  1164.             *pkeywords = PyDict_New();
  1165.         if (v == NULL || *pkeywords == NULL)
  1166.             c->c_errors++;
  1167.         else {
  1168.             if (PyDict_GetItem(*pkeywords, v) != NULL)
  1169.                 com_error(c, PyExc_SyntaxError,
  1170.                       "duplicate keyword argument");
  1171.             else
  1172.                 if (PyDict_SetItem(*pkeywords, v, v) != 0)
  1173.                     c->c_errors++;
  1174.             com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  1175.             com_push(c, 1);
  1176.             Py_DECREF(v);
  1177.         }
  1178.     }
  1179.     com_node(c, CHILD(n, 2));
  1180. }
  1181.  
  1182. static void
  1183. com_call_function(c, n)
  1184.     struct compiling *c;
  1185.     node *n; /* EITHER arglist OR ')' */
  1186. {
  1187.     if (TYPE(n) == RPAR) {
  1188.         com_addoparg(c, CALL_FUNCTION, 0);
  1189.     }
  1190.     else {
  1191.         PyObject *keywords = NULL;
  1192.         int i, na, nk;
  1193.         int lineno = n->n_lineno;
  1194.         int star_flag = 0;
  1195.         int starstar_flag = 0;
  1196.         int opcode;
  1197.         REQ(n, arglist);
  1198.         na = 0;
  1199.         nk = 0;
  1200.         for (i = 0; i < NCH(n); i += 2) {
  1201.             node *ch = CHILD(n, i);
  1202.             if (TYPE(ch) == STAR ||
  1203.                 TYPE(ch) == DOUBLESTAR)
  1204.               break;
  1205.             if (ch->n_lineno != lineno) {
  1206.                 lineno = ch->n_lineno;
  1207.                 com_addoparg(c, SET_LINENO, lineno);
  1208.             }
  1209.             com_argument(c, ch, &keywords);
  1210.             if (keywords == NULL)
  1211.                 na++;
  1212.             else
  1213.                 nk++;
  1214.         }
  1215.         Py_XDECREF(keywords);
  1216.         while (i < NCH(n)) {
  1217.             node *tok = CHILD(n, i);
  1218.             node *ch = CHILD(n, i+1);
  1219.             i += 3;
  1220.             switch (TYPE(tok)) {
  1221.             case STAR:       star_flag = 1;     break;
  1222.             case DOUBLESTAR: starstar_flag = 1;    break;
  1223.             }
  1224.             com_node(c, ch);
  1225.         }
  1226.         if (na > 255 || nk > 255) {
  1227.             com_error(c, PyExc_SyntaxError,
  1228.                   "more than 255 arguments");
  1229.         }
  1230.         if (star_flag || starstar_flag)
  1231.             opcode = CALL_FUNCTION_VAR - 1 + 
  1232.             star_flag + (starstar_flag << 1);
  1233.         else
  1234.             opcode = CALL_FUNCTION;
  1235.         com_addoparg(c, opcode, na | (nk << 8));
  1236.         com_pop(c, na + 2*nk + star_flag + starstar_flag);
  1237.     }
  1238. }
  1239.  
  1240. static void
  1241. com_select_member(c, n)
  1242.     struct compiling *c;
  1243.     node *n;
  1244. {
  1245.     com_addopname(c, LOAD_ATTR, n);
  1246. }
  1247.  
  1248. static void
  1249. com_sliceobj(c, n)
  1250.     struct compiling *c;
  1251.     node *n;
  1252. {
  1253.     int i=0;
  1254.     int ns=2; /* number of slice arguments */
  1255.     node *ch;
  1256.  
  1257.     /* first argument */
  1258.     if (TYPE(CHILD(n,i)) == COLON) {
  1259.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1260.         com_push(c, 1);
  1261.         i++;
  1262.     }
  1263.     else {
  1264.         com_node(c, CHILD(n,i));
  1265.         i++;
  1266.         REQ(CHILD(n,i),COLON);
  1267.         i++;
  1268.     }
  1269.     /* second argument */
  1270.     if (i < NCH(n) && TYPE(CHILD(n,i)) == test) {
  1271.         com_node(c, CHILD(n,i));
  1272.         i++;
  1273.     }
  1274.     else {
  1275.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1276.         com_push(c, 1);
  1277.     }
  1278.     /* remaining arguments */
  1279.     for (; i < NCH(n); i++) {
  1280.         ns++;
  1281.         ch=CHILD(n,i);
  1282.         REQ(ch, sliceop);
  1283.         if (NCH(ch) == 1) {
  1284.             /* right argument of ':' missing */
  1285.             com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1286.             com_push(c, 1);
  1287.         }
  1288.         else
  1289.             com_node(c, CHILD(ch,1));
  1290.     }
  1291.     com_addoparg(c, BUILD_SLICE, ns);
  1292.     com_pop(c, 1 + (ns == 3));
  1293. }
  1294.  
  1295. static void
  1296. com_subscript(c, n)
  1297.     struct compiling *c;
  1298.     node *n;
  1299. {
  1300.     node *ch;
  1301.     REQ(n, subscript);
  1302.     ch = CHILD(n,0);
  1303.     /* check for rubber index */
  1304.     if (TYPE(ch) == DOT && TYPE(CHILD(n,1)) == DOT) {
  1305.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_Ellipsis));
  1306.         com_push(c, 1);
  1307.     }
  1308.     else {
  1309.         /* check for slice */
  1310.         if ((TYPE(ch) == COLON || NCH(n) > 1))
  1311.             com_sliceobj(c, n);
  1312.         else {
  1313.             REQ(ch, test);
  1314.             com_node(c, ch);
  1315.         }
  1316.     }
  1317. }
  1318.  
  1319. static void
  1320. com_subscriptlist(c, n, assigning)
  1321.     struct compiling *c;
  1322.     node *n;
  1323.     int assigning;
  1324. {
  1325.     int i, op;
  1326.     REQ(n, subscriptlist);
  1327.     /* Check to make backward compatible slice behavior for '[i:j]' */
  1328.     if (NCH(n) == 1) {
  1329.         node *sub = CHILD(n, 0); /* subscript */
  1330.         /* Make it is a simple slice.
  1331.            Should have exactly one colon. */
  1332.         if ((TYPE(CHILD(sub, 0)) == COLON
  1333.              || (NCH(sub) > 1 && TYPE(CHILD(sub, 1)) == COLON))
  1334.             && (TYPE(CHILD(sub,NCH(sub)-1)) != sliceop))
  1335.     {
  1336.             if (assigning == OP_APPLY)
  1337.                 op = SLICE;
  1338.             else
  1339.                 op = ((assigning == OP_ASSIGN) ?
  1340.                       STORE_SLICE : DELETE_SLICE);
  1341.             com_slice(c, sub, op);
  1342.             if (op == STORE_SLICE)
  1343.                 com_pop(c, 2);
  1344.             else if (op == DELETE_SLICE)
  1345.                 com_pop(c, 1);
  1346.             return;
  1347.         }
  1348.     }
  1349.     /* Else normal subscriptlist.  Compile each subscript. */
  1350.     for (i = 0; i < NCH(n); i += 2)
  1351.         com_subscript(c, CHILD(n, i));
  1352.     /* Put multiple subscripts into a tuple */
  1353.     if (NCH(n) > 1) {
  1354.         i = (NCH(n)+1) / 2;
  1355.         com_addoparg(c, BUILD_TUPLE, i);
  1356.         com_pop(c, i-1);
  1357.     }
  1358.     if (assigning == OP_APPLY) {
  1359.         op = BINARY_SUBSCR;
  1360.         i = 1;
  1361.     }
  1362.     else if (assigning == OP_ASSIGN) {
  1363.         op = STORE_SUBSCR;
  1364.         i = 3;
  1365.     }
  1366.     else {
  1367.         op = DELETE_SUBSCR;
  1368.         i = 2;
  1369.     }
  1370.     com_addbyte(c, op);
  1371.     com_pop(c, i);
  1372. }
  1373.  
  1374. static void
  1375. com_apply_trailer(c, n)
  1376.     struct compiling *c;
  1377.     node *n;
  1378. {
  1379.     REQ(n, trailer);
  1380.     switch (TYPE(CHILD(n, 0))) {
  1381.     case LPAR:
  1382.         com_call_function(c, CHILD(n, 1));
  1383.         break;
  1384.     case DOT:
  1385.         com_select_member(c, CHILD(n, 1));
  1386.         break;
  1387.     case LSQB:
  1388.         com_subscriptlist(c, CHILD(n, 1), OP_APPLY);
  1389.         break;
  1390.     default:
  1391.         com_error(c, PyExc_SystemError,
  1392.               "com_apply_trailer: unknown trailer type");
  1393.     }
  1394. }
  1395.  
  1396. static void
  1397. com_power(c, n)
  1398.     struct compiling *c;
  1399.     node *n;
  1400. {
  1401.     int i;
  1402.     REQ(n, power);
  1403.     com_atom(c, CHILD(n, 0));
  1404.     for (i = 1; i < NCH(n); i++) {
  1405.         if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1406.             com_factor(c, CHILD(n, i+1));
  1407.             com_addbyte(c, BINARY_POWER);
  1408.             com_pop(c, 1);
  1409.             break;
  1410.         }
  1411.         else
  1412.             com_apply_trailer(c, CHILD(n, i));
  1413.     }
  1414. }
  1415.  
  1416. static void
  1417. com_factor(c, n)
  1418.     struct compiling *c;
  1419.     node *n;
  1420. {
  1421.     REQ(n, factor);
  1422.     if (TYPE(CHILD(n, 0)) == PLUS) {
  1423.         com_factor(c, CHILD(n, 1));
  1424.         com_addbyte(c, UNARY_POSITIVE);
  1425.     }
  1426.     else if (TYPE(CHILD(n, 0)) == MINUS) {
  1427.         com_factor(c, CHILD(n, 1));
  1428.         com_addbyte(c, UNARY_NEGATIVE);
  1429.     }
  1430.     else if (TYPE(CHILD(n, 0)) == TILDE) {
  1431.         com_factor(c, CHILD(n, 1));
  1432.         com_addbyte(c, UNARY_INVERT);
  1433.     }
  1434.     else {
  1435.         com_power(c, CHILD(n, 0));
  1436.     }
  1437. }
  1438.  
  1439. static void
  1440. com_term(c, n)
  1441.     struct compiling *c;
  1442.     node *n;
  1443. {
  1444.     int i;
  1445.     int op;
  1446.     REQ(n, term);
  1447.     com_factor(c, CHILD(n, 0));
  1448.     for (i = 2; i < NCH(n); i += 2) {
  1449.         com_factor(c, CHILD(n, i));
  1450.         switch (TYPE(CHILD(n, i-1))) {
  1451.         case STAR:
  1452.             op = BINARY_MULTIPLY;
  1453.             break;
  1454.         case SLASH:
  1455.             op = BINARY_DIVIDE;
  1456.             break;
  1457.         case PERCENT:
  1458.             op = BINARY_MODULO;
  1459.             break;
  1460.         default:
  1461.             com_error(c, PyExc_SystemError,
  1462.                   "com_term: operator not *, / or %");
  1463.             op = 255;
  1464.         }
  1465.         com_addbyte(c, op);
  1466.         com_pop(c, 1);
  1467.     }
  1468. }
  1469.  
  1470. static void
  1471. com_arith_expr(c, n)
  1472.     struct compiling *c;
  1473.     node *n;
  1474. {
  1475.     int i;
  1476.     int op;
  1477.     REQ(n, arith_expr);
  1478.     com_term(c, CHILD(n, 0));
  1479.     for (i = 2; i < NCH(n); i += 2) {
  1480.         com_term(c, CHILD(n, i));
  1481.         switch (TYPE(CHILD(n, i-1))) {
  1482.         case PLUS:
  1483.             op = BINARY_ADD;
  1484.             break;
  1485.         case MINUS:
  1486.             op = BINARY_SUBTRACT;
  1487.             break;
  1488.         default:
  1489.             com_error(c, PyExc_SystemError,
  1490.                   "com_arith_expr: operator not + or -");
  1491.             op = 255;
  1492.         }
  1493.         com_addbyte(c, op);
  1494.         com_pop(c, 1);
  1495.     }
  1496. }
  1497.  
  1498. static void
  1499. com_shift_expr(c, n)
  1500.     struct compiling *c;
  1501.     node *n;
  1502. {
  1503.     int i;
  1504.     int op;
  1505.     REQ(n, shift_expr);
  1506.     com_arith_expr(c, CHILD(n, 0));
  1507.     for (i = 2; i < NCH(n); i += 2) {
  1508.         com_arith_expr(c, CHILD(n, i));
  1509.         switch (TYPE(CHILD(n, i-1))) {
  1510.         case LEFTSHIFT:
  1511.             op = BINARY_LSHIFT;
  1512.             break;
  1513.         case RIGHTSHIFT:
  1514.             op = BINARY_RSHIFT;
  1515.             break;
  1516.         default:
  1517.             com_error(c, PyExc_SystemError,
  1518.                   "com_shift_expr: operator not << or >>");
  1519.             op = 255;
  1520.         }
  1521.         com_addbyte(c, op);
  1522.         com_pop(c, 1);
  1523.     }
  1524. }
  1525.  
  1526. static void
  1527. com_and_expr(c, n)
  1528.     struct compiling *c;
  1529.     node *n;
  1530. {
  1531.     int i;
  1532.     int op;
  1533.     REQ(n, and_expr);
  1534.     com_shift_expr(c, CHILD(n, 0));
  1535.     for (i = 2; i < NCH(n); i += 2) {
  1536.         com_shift_expr(c, CHILD(n, i));
  1537.         if (TYPE(CHILD(n, i-1)) == AMPER) {
  1538.             op = BINARY_AND;
  1539.         }
  1540.         else {
  1541.             com_error(c, PyExc_SystemError,
  1542.                   "com_and_expr: operator not &");
  1543.             op = 255;
  1544.         }
  1545.         com_addbyte(c, op);
  1546.         com_pop(c, 1);
  1547.     }
  1548. }
  1549.  
  1550. static void
  1551. com_xor_expr(c, n)
  1552.     struct compiling *c;
  1553.     node *n;
  1554. {
  1555.     int i;
  1556.     int op;
  1557.     REQ(n, xor_expr);
  1558.     com_and_expr(c, CHILD(n, 0));
  1559.     for (i = 2; i < NCH(n); i += 2) {
  1560.         com_and_expr(c, CHILD(n, i));
  1561.         if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
  1562.             op = BINARY_XOR;
  1563.         }
  1564.         else {
  1565.             com_error(c, PyExc_SystemError,
  1566.                   "com_xor_expr: operator not ^");
  1567.             op = 255;
  1568.         }
  1569.         com_addbyte(c, op);
  1570.         com_pop(c, 1);
  1571.     }
  1572. }
  1573.  
  1574. static void
  1575. com_expr(c, n)
  1576.     struct compiling *c;
  1577.     node *n;
  1578. {
  1579.     int i;
  1580.     int op;
  1581.     REQ(n, expr);
  1582.     com_xor_expr(c, CHILD(n, 0));
  1583.     for (i = 2; i < NCH(n); i += 2) {
  1584.         com_xor_expr(c, CHILD(n, i));
  1585.         if (TYPE(CHILD(n, i-1)) == VBAR) {
  1586.             op = BINARY_OR;
  1587.         }
  1588.         else {
  1589.             com_error(c, PyExc_SystemError,
  1590.                   "com_expr: expr operator not |");
  1591.             op = 255;
  1592.         }
  1593.         com_addbyte(c, op);
  1594.         com_pop(c, 1);
  1595.     }
  1596. }
  1597.  
  1598. static enum cmp_op
  1599. cmp_type(n)
  1600.     node *n;
  1601. {
  1602.     REQ(n, comp_op);
  1603.     /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
  1604.               | 'in' | 'not' 'in' | 'is' | 'is' not' */
  1605.     if (NCH(n) == 1) {
  1606.         n = CHILD(n, 0);
  1607.         switch (TYPE(n)) {
  1608.         case LESS:    return LT;
  1609.         case GREATER:    return GT;
  1610.         case EQEQUAL:            /* == */
  1611.         case EQUAL:    return EQ;
  1612.         case LESSEQUAL:    return LE;
  1613.         case GREATEREQUAL: return GE;
  1614.         case NOTEQUAL:    return NE;    /* <> or != */
  1615.         case NAME:    if (strcmp(STR(n), "in") == 0) return IN;
  1616.                 if (strcmp(STR(n), "is") == 0) return IS;
  1617.         }
  1618.     }
  1619.     else if (NCH(n) == 2) {
  1620.         switch (TYPE(CHILD(n, 0))) {
  1621.         case NAME:    if (strcmp(STR(CHILD(n, 1)), "in") == 0)
  1622.                     return NOT_IN;
  1623.                 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
  1624.                     return IS_NOT;
  1625.         }
  1626.     }
  1627.     return BAD;
  1628. }
  1629.  
  1630. static void
  1631. com_comparison(c, n)
  1632.     struct compiling *c;
  1633.     node *n;
  1634. {
  1635.     int i;
  1636.     enum cmp_op op;
  1637.     int anchor;
  1638.     REQ(n, comparison); /* comparison: expr (comp_op expr)* */
  1639.     com_expr(c, CHILD(n, 0));
  1640.     if (NCH(n) == 1)
  1641.         return;
  1642.     
  1643.     /****************************************************************
  1644.        The following code is generated for all but the last
  1645.        comparison in a chain:
  1646.        
  1647.        label:    on stack:    opcode:        jump to:
  1648.        
  1649.             a        <code to load b>
  1650.             a, b        DUP_TOP
  1651.             a, b, b        ROT_THREE
  1652.             b, a, b        COMPARE_OP
  1653.             b, 0-or-1    JUMP_IF_FALSE    L1
  1654.             b, 1        POP_TOP
  1655.             b        
  1656.     
  1657.        We are now ready to repeat this sequence for the next
  1658.        comparison in the chain.
  1659.        
  1660.        For the last we generate:
  1661.        
  1662.                b        <code to load c>
  1663.                b, c        COMPARE_OP
  1664.                0-or-1        
  1665.        
  1666.        If there were any jumps to L1 (i.e., there was more than one
  1667.        comparison), we generate:
  1668.        
  1669.                0-or-1        JUMP_FORWARD    L2
  1670.        L1:        b, 0        ROT_TWO
  1671.                0, b        POP_TOP
  1672.                0
  1673.        L2:        0-or-1
  1674.     ****************************************************************/
  1675.     
  1676.     anchor = 0;
  1677.     
  1678.     for (i = 2; i < NCH(n); i += 2) {
  1679.         com_expr(c, CHILD(n, i));
  1680.         if (i+2 < NCH(n)) {
  1681.             com_addbyte(c, DUP_TOP);
  1682.             com_push(c, 1);
  1683.             com_addbyte(c, ROT_THREE);
  1684.         }
  1685.         op = cmp_type(CHILD(n, i-1));
  1686.         if (op == BAD) {
  1687.             com_error(c, PyExc_SystemError,
  1688.                   "com_comparison: unknown comparison op");
  1689.         }
  1690.         com_addoparg(c, COMPARE_OP, op);
  1691.         com_pop(c, 1);
  1692.         if (i+2 < NCH(n)) {
  1693.             com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1694.             com_addbyte(c, POP_TOP);
  1695.             com_pop(c, 1);
  1696.         }
  1697.     }
  1698.     
  1699.     if (anchor) {
  1700.         int anchor2 = 0;
  1701.         com_addfwref(c, JUMP_FORWARD, &anchor2);
  1702.         com_backpatch(c, anchor);
  1703.         com_addbyte(c, ROT_TWO);
  1704.         com_addbyte(c, POP_TOP);
  1705.         com_backpatch(c, anchor2);
  1706.     }
  1707. }
  1708.  
  1709. static void
  1710. com_not_test(c, n)
  1711.     struct compiling *c;
  1712.     node *n;
  1713. {
  1714.     REQ(n, not_test); /* 'not' not_test | comparison */
  1715.     if (NCH(n) == 1) {
  1716.         com_comparison(c, CHILD(n, 0));
  1717.     }
  1718.     else {
  1719.         com_not_test(c, CHILD(n, 1));
  1720.         com_addbyte(c, UNARY_NOT);
  1721.     }
  1722. }
  1723.  
  1724. static void
  1725. com_and_test(c, n)
  1726.     struct compiling *c;
  1727.     node *n;
  1728. {
  1729.     int i;
  1730.     int anchor;
  1731.     REQ(n, and_test); /* not_test ('and' not_test)* */
  1732.     anchor = 0;
  1733.     i = 0;
  1734.     for (;;) {
  1735.         com_not_test(c, CHILD(n, i));
  1736.         if ((i += 2) >= NCH(n))
  1737.             break;
  1738.         com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1739.         com_addbyte(c, POP_TOP);
  1740.         com_pop(c, 1);
  1741.     }
  1742.     if (anchor)
  1743.         com_backpatch(c, anchor);
  1744. }
  1745.  
  1746. static void
  1747. com_test(c, n)
  1748.     struct compiling *c;
  1749.     node *n;
  1750. {
  1751.     REQ(n, test); /* and_test ('or' and_test)* | lambdef */
  1752.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) {
  1753.         PyObject *v;
  1754.         int i;
  1755.         int ndefs = com_argdefs(c, CHILD(n, 0));
  1756.         v = (PyObject *) icompile(CHILD(n, 0), c);
  1757.         if (v == NULL) {
  1758.             c->c_errors++;
  1759.             i = 255;
  1760.         }
  1761.         else {
  1762.             i = com_addconst(c, v);
  1763.             Py_DECREF(v);
  1764.         }
  1765.         com_addoparg(c, LOAD_CONST, i);
  1766.         com_push(c, 1);
  1767.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  1768.         com_pop(c, ndefs);
  1769.     }
  1770.     else {
  1771.         int anchor = 0;
  1772.         int i = 0;
  1773.         for (;;) {
  1774.             com_and_test(c, CHILD(n, i));
  1775.             if ((i += 2) >= NCH(n))
  1776.                 break;
  1777.             com_addfwref(c, JUMP_IF_TRUE, &anchor);
  1778.             com_addbyte(c, POP_TOP);
  1779.             com_pop(c, 1);
  1780.         }
  1781.         if (anchor)
  1782.             com_backpatch(c, anchor);
  1783.     }
  1784. }
  1785.  
  1786. static void
  1787. com_list(c, n, toplevel)
  1788.     struct compiling *c;
  1789.     node *n;
  1790.     int toplevel; /* If nonzero, *always* build a tuple */
  1791. {
  1792.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1793.     if (NCH(n) == 1 && !toplevel) {
  1794.         com_node(c, CHILD(n, 0));
  1795.     }
  1796.     else {
  1797.         int i;
  1798.         int len;
  1799.         len = (NCH(n) + 1) / 2;
  1800.         for (i = 0; i < NCH(n); i += 2)
  1801.             com_node(c, CHILD(n, i));
  1802.         com_addoparg(c, BUILD_TUPLE, len);
  1803.         com_pop(c, len-1);
  1804.     }
  1805. }
  1806.  
  1807.  
  1808. /* Begin of assignment compilation */
  1809.  
  1810. static void com_assign_name Py_PROTO((struct compiling *, node *, int));
  1811. static void com_assign Py_PROTO((struct compiling *, node *, int));
  1812.  
  1813. static void
  1814. com_assign_attr(c, n, assigning)
  1815.     struct compiling *c;
  1816.     node *n;
  1817.     int assigning;
  1818. {
  1819.     com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
  1820.     com_pop(c, assigning ? 2 : 1);
  1821. }
  1822.  
  1823. static void
  1824. com_assign_trailer(c, n, assigning)
  1825.     struct compiling *c;
  1826.     node *n;
  1827.     int assigning;
  1828. {
  1829.     REQ(n, trailer);
  1830.     switch (TYPE(CHILD(n, 0))) {
  1831.     case LPAR: /* '(' [exprlist] ')' */
  1832.         com_error(c, PyExc_SyntaxError,
  1833.               "can't assign to function call");
  1834.         break;
  1835.     case DOT: /* '.' NAME */
  1836.         com_assign_attr(c, CHILD(n, 1), assigning);
  1837.         break;
  1838.     case LSQB: /* '[' subscriptlist ']' */
  1839.         com_subscriptlist(c, CHILD(n, 1), assigning);
  1840.         break;
  1841.     default:
  1842.         com_error(c, PyExc_SystemError, "unknown trailer type");
  1843.     }
  1844. }
  1845.  
  1846. static void
  1847. com_assign_tuple(c, n, assigning)
  1848.     struct compiling *c;
  1849.     node *n;
  1850.     int assigning;
  1851. {
  1852.     int i;
  1853.     if (TYPE(n) != testlist)
  1854.         REQ(n, exprlist);
  1855.     if (assigning) {
  1856.         i = (NCH(n)+1)/2;
  1857.         com_addoparg(c, UNPACK_TUPLE, i);
  1858.         com_push(c, i-1);
  1859.     }
  1860.     for (i = 0; i < NCH(n); i += 2)
  1861.         com_assign(c, CHILD(n, i), assigning);
  1862. }
  1863.  
  1864. static void
  1865. com_assign_list(c, n, assigning)
  1866.     struct compiling *c;
  1867.     node *n;
  1868.     int assigning;
  1869. {
  1870.     int i;
  1871.     if (assigning) {
  1872.         i = (NCH(n)+1)/2;
  1873.         com_addoparg(c, UNPACK_LIST, i);
  1874.         com_push(c, i-1);
  1875.     }
  1876.     for (i = 0; i < NCH(n); i += 2)
  1877.         com_assign(c, CHILD(n, i), assigning);
  1878. }
  1879.  
  1880. static void
  1881. com_assign_name(c, n, assigning)
  1882.     struct compiling *c;
  1883.     node *n;
  1884.     int assigning;
  1885. {
  1886.     REQ(n, NAME);
  1887.     com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
  1888.     if (assigning)
  1889.         com_pop(c, 1);
  1890. }
  1891.  
  1892. static void
  1893. com_assign(c, n, assigning)
  1894.     struct compiling *c;
  1895.     node *n;
  1896.     int assigning;
  1897. {
  1898.     /* Loop to avoid trivial recursion */
  1899.     for (;;) {
  1900.         switch (TYPE(n)) {
  1901.         
  1902.         case exprlist:
  1903.         case testlist:
  1904.             if (NCH(n) > 1) {
  1905.                 com_assign_tuple(c, n, assigning);
  1906.                 return;
  1907.             }
  1908.             n = CHILD(n, 0);
  1909.             break;
  1910.         
  1911.         case test:
  1912.         case and_test:
  1913.         case not_test:
  1914.         case comparison:
  1915.         case expr:
  1916.         case xor_expr:
  1917.         case and_expr:
  1918.         case shift_expr:
  1919.         case arith_expr:
  1920.         case term:
  1921.         case factor:
  1922.             if (NCH(n) > 1) {
  1923.                 com_error(c, PyExc_SyntaxError,
  1924.                       "can't assign to operator");
  1925.                 return;
  1926.             }
  1927.             n = CHILD(n, 0);
  1928.             break;
  1929.         
  1930.         case power: /* atom trailer* ('**' power)* */
  1931. /* ('+'|'-'|'~') factor | atom trailer* */
  1932.             if (TYPE(CHILD(n, 0)) != atom) {
  1933.                 com_error(c, PyExc_SyntaxError,
  1934.                       "can't assign to operator");
  1935.                 return;
  1936.             }
  1937.             if (NCH(n) > 1) { /* trailer or exponent present */
  1938.                 int i;
  1939.                 com_node(c, CHILD(n, 0));
  1940.                 for (i = 1; i+1 < NCH(n); i++) {
  1941.                     if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1942.                         com_error(c, PyExc_SyntaxError,
  1943.                           "can't assign to operator");
  1944.                         return;
  1945.                     }
  1946.                     com_apply_trailer(c, CHILD(n, i));
  1947.                 } /* NB i is still alive */
  1948.                 com_assign_trailer(c,
  1949.                         CHILD(n, i), assigning);
  1950.                 return;
  1951.             }
  1952.             n = CHILD(n, 0);
  1953.             break;
  1954.         
  1955.         case atom:
  1956.             switch (TYPE(CHILD(n, 0))) {
  1957.             case LPAR:
  1958.                 n = CHILD(n, 1);
  1959.                 if (TYPE(n) == RPAR) {
  1960.                     /* XXX Should allow () = () ??? */
  1961.                     com_error(c, PyExc_SyntaxError,
  1962.                           "can't assign to ()");
  1963.                     return;
  1964.                 }
  1965.                 break;
  1966.             case LSQB:
  1967.                 n = CHILD(n, 1);
  1968.                 if (TYPE(n) == RSQB) {
  1969.                     com_error(c, PyExc_SyntaxError,
  1970.                           "can't assign to []");
  1971.                     return;
  1972.                 }
  1973.                 com_assign_list(c, n, assigning);
  1974.                 return;
  1975.             case NAME:
  1976.                 com_assign_name(c, CHILD(n, 0), assigning);
  1977.                 return;
  1978.             default:
  1979.                 com_error(c, PyExc_SyntaxError,
  1980.                       "can't assign to literal");
  1981.                 return;
  1982.             }
  1983.             break;
  1984.  
  1985.         case lambdef:
  1986.             com_error(c, PyExc_SyntaxError,
  1987.                   "can't assign to lambda");
  1988.             return;
  1989.         
  1990.         default:
  1991.             /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  1992.             com_error(c, PyExc_SystemError,
  1993.                   "com_assign: bad node");
  1994.             return;
  1995.         
  1996.         }
  1997.     }
  1998. }
  1999.  
  2000. /* Forward */ static node *get_rawdocstring Py_PROTO((node *));
  2001.  
  2002. static void
  2003. com_expr_stmt(c, n)
  2004.     struct compiling *c;
  2005.     node *n;
  2006. {
  2007.     REQ(n, expr_stmt); /* testlist ('=' testlist)* */
  2008.     /* Forget it if we have just a doc string here */
  2009.     if (!c->c_interactive && NCH(n) == 1 && get_rawdocstring(n) != NULL)
  2010.         return;
  2011.     com_node(c, CHILD(n, NCH(n)-1));
  2012.     if (NCH(n) == 1) {
  2013.         if (c->c_interactive)
  2014.             com_addbyte(c, PRINT_EXPR);
  2015.         else
  2016.             com_addbyte(c, POP_TOP);
  2017.         com_pop(c, 1);
  2018.     }
  2019.     else {
  2020.         int i;
  2021.         for (i = 0; i < NCH(n)-2; i+=2) {
  2022.             if (i+2 < NCH(n)-2) {
  2023.                 com_addbyte(c, DUP_TOP);
  2024.                 com_push(c, 1);
  2025.             }
  2026.             com_assign(c, CHILD(n, i), OP_ASSIGN);
  2027.         }
  2028.     }
  2029. }
  2030.  
  2031. static void
  2032. com_assert_stmt(c, n)
  2033.     struct compiling *c;
  2034.     node *n;
  2035. {
  2036.     int a = 0, b = 0;
  2037.     int i;
  2038.     REQ(n, assert_stmt); /* 'assert' test [',' test] */
  2039.     /* Generate code like for
  2040.        
  2041.        if __debug__:
  2042.           if not <test>:
  2043.              raise AssertionError [, <message>]
  2044.  
  2045.        where <message> is the second test, if present.
  2046.     */
  2047.     if (Py_OptimizeFlag)
  2048.         return;
  2049.     com_addopnamestr(c, LOAD_GLOBAL, "__debug__");
  2050.     com_push(c, 1);
  2051.     com_addfwref(c, JUMP_IF_FALSE, &a);
  2052.     com_addbyte(c, POP_TOP);
  2053.     com_pop(c, 1);
  2054.     com_node(c, CHILD(n, 1));
  2055.     com_addfwref(c, JUMP_IF_TRUE, &b);
  2056.     com_addbyte(c, POP_TOP);
  2057.     com_pop(c, 1);
  2058.     /* Raise that exception! */
  2059.     com_addopnamestr(c, LOAD_GLOBAL, "AssertionError");
  2060.     com_push(c, 1);
  2061.     i = NCH(n)/2; /* Either 2 or 4 */
  2062.     if (i > 1)
  2063.         com_node(c, CHILD(n, 3));
  2064.     com_addoparg(c, RAISE_VARARGS, i);
  2065.     com_pop(c, i);
  2066.     /* The interpreter does not fall through */
  2067.     /* All jumps converge here */
  2068.     com_backpatch(c, a);
  2069.     com_backpatch(c, b);
  2070.     com_addbyte(c, POP_TOP);
  2071. }
  2072.  
  2073. static void
  2074. com_print_stmt(c, n)
  2075.     struct compiling *c;
  2076.     node *n;
  2077. {
  2078.     int i;
  2079.     REQ(n, print_stmt); /* 'print' (test ',')* [test] */
  2080.     for (i = 1; i < NCH(n); i += 2) {
  2081.         com_node(c, CHILD(n, i));
  2082.         com_addbyte(c, PRINT_ITEM);
  2083.         com_pop(c, 1);
  2084.     }
  2085.     if (TYPE(CHILD(n, NCH(n)-1)) != COMMA)
  2086.         com_addbyte(c, PRINT_NEWLINE);
  2087.         /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
  2088. }
  2089.  
  2090. static void
  2091. com_return_stmt(c, n)
  2092.     struct compiling *c;
  2093.     node *n;
  2094. {
  2095.     REQ(n, return_stmt); /* 'return' [testlist] */
  2096.     if (!c->c_infunction) {
  2097.         com_error(c, PyExc_SyntaxError, "'return' outside function");
  2098.     }
  2099.     if (NCH(n) < 2) {
  2100.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2101.         com_push(c, 1);
  2102.     }
  2103.     else
  2104.         com_node(c, CHILD(n, 1));
  2105.     com_addbyte(c, RETURN_VALUE);
  2106.     com_pop(c, 1);
  2107. }
  2108.  
  2109. static void
  2110. com_raise_stmt(c, n)
  2111.     struct compiling *c;
  2112.     node *n;
  2113. {
  2114.     int i;
  2115.     REQ(n, raise_stmt); /* 'raise' [test [',' test [',' test]]] */
  2116.     if (NCH(n) > 1) {
  2117.         com_node(c, CHILD(n, 1));
  2118.         if (NCH(n) > 3) {
  2119.             com_node(c, CHILD(n, 3));
  2120.             if (NCH(n) > 5)
  2121.                 com_node(c, CHILD(n, 5));
  2122.         }
  2123.     }
  2124.     i = NCH(n)/2;
  2125.     com_addoparg(c, RAISE_VARARGS, i);
  2126.     com_pop(c, i);
  2127. }
  2128.  
  2129. static void
  2130. com_import_stmt(c, n)
  2131.     struct compiling *c;
  2132.     node *n;
  2133. {
  2134.     int i;
  2135.     REQ(n, import_stmt);
  2136.     /* 'import' dotted_name (',' dotted_name)* |
  2137.        'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
  2138.     if (STR(CHILD(n, 0))[0] == 'f') {
  2139.         /* 'from' dotted_name 'import' ... */
  2140.         REQ(CHILD(n, 1), dotted_name);
  2141.         com_addopname(c, IMPORT_NAME, CHILD(n, 1));
  2142.         com_push(c, 1);
  2143.         for (i = 3; i < NCH(n); i += 2)
  2144.             com_addopname(c, IMPORT_FROM, CHILD(n, i));
  2145.         com_addbyte(c, POP_TOP);
  2146.         com_pop(c, 1);
  2147.     }
  2148.     else {
  2149.         /* 'import' ... */
  2150.         for (i = 1; i < NCH(n); i += 2) {
  2151.             REQ(CHILD(n, i), dotted_name);
  2152.             com_addopname(c, IMPORT_NAME, CHILD(n, i));
  2153.             com_push(c, 1);
  2154.             com_addopname(c, STORE_NAME, CHILD(CHILD(n, i), 0));
  2155.             com_pop(c, 1);
  2156.         }
  2157.     }
  2158. }
  2159.  
  2160. static void
  2161. com_global_stmt(c, n)
  2162.     struct compiling *c;
  2163.     node *n;
  2164. {
  2165.     int i;
  2166.     REQ(n, global_stmt);
  2167.     /* 'global' NAME (',' NAME)* */
  2168.     for (i = 1; i < NCH(n); i += 2) {
  2169.         char *s = STR(CHILD(n, i));
  2170. #ifdef PRIVATE_NAME_MANGLING
  2171.         char buffer[256];
  2172.         if (s != NULL && s[0] == '_' && s[1] == '_' &&
  2173.             c->c_private != NULL &&
  2174.             com_mangle(c, s, buffer, (int)sizeof(buffer)))
  2175.             s = buffer;
  2176. #endif
  2177.         if (PyDict_GetItemString(c->c_locals, s) != NULL) {
  2178.             com_error(c, PyExc_SyntaxError,
  2179.                   "name is local and global");
  2180.         }
  2181.         else if (PyDict_SetItemString(c->c_globals, s, Py_None) != 0)
  2182.             c->c_errors++;
  2183.     }
  2184. }
  2185.  
  2186. static int
  2187. com_newlocal_o(c, nameval)
  2188.     struct compiling *c;
  2189.     PyObject *nameval;
  2190. {
  2191.     int i;
  2192.     PyObject *ival;
  2193.     if (PyList_Size(c->c_varnames) != c->c_nlocals) {
  2194.         /* This is usually caused by an error on a previous call */
  2195.         if (c->c_errors == 0) {
  2196.             com_error(c, PyExc_SystemError,
  2197.                   "mixed up var name/index");
  2198.         }
  2199.         return 0;
  2200.     }
  2201.     ival = PyInt_FromLong(i = c->c_nlocals++);
  2202.     if (ival == NULL)
  2203.         c->c_errors++;
  2204.     else if (PyDict_SetItem(c->c_locals, nameval, ival) != 0)
  2205.         c->c_errors++;
  2206.     else if (PyList_Append(c->c_varnames, nameval) != 0)
  2207.         c->c_errors++;
  2208.     Py_XDECREF(ival);
  2209.     return i;
  2210. }
  2211.  
  2212. static int
  2213. com_addlocal_o(c, nameval)
  2214.     struct compiling *c;
  2215.     PyObject *nameval;
  2216. {
  2217.     PyObject *ival =  PyDict_GetItem(c->c_locals, nameval);
  2218.     if (ival != NULL)
  2219.         return PyInt_AsLong(ival);
  2220.     return com_newlocal_o(c, nameval);
  2221. }
  2222.  
  2223. static int
  2224. com_newlocal(c, name)
  2225.     struct compiling *c;
  2226.     char *name;
  2227. {
  2228.     PyObject *nameval = PyString_InternFromString(name);
  2229.     int i;
  2230.     if (nameval == NULL) {
  2231.         c->c_errors++;
  2232.         return 0;
  2233.     }
  2234.     i = com_newlocal_o(c, nameval);
  2235.     Py_DECREF(nameval);
  2236.     return i;
  2237. }
  2238.  
  2239. static void
  2240. com_exec_stmt(c, n)
  2241.     struct compiling *c;
  2242.     node *n;
  2243. {
  2244.     REQ(n, exec_stmt);
  2245.     /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
  2246.     com_node(c, CHILD(n, 1));
  2247.     if (NCH(n) >= 4)
  2248.         com_node(c, CHILD(n, 3));
  2249.     else {
  2250.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2251.         com_push(c, 1);
  2252.     }
  2253.     if (NCH(n) >= 6)
  2254.         com_node(c, CHILD(n, 5));
  2255.     else {
  2256.         com_addbyte(c, DUP_TOP);
  2257.         com_push(c, 1);
  2258.     }
  2259.     com_addbyte(c, EXEC_STMT);
  2260.     com_pop(c, 3);
  2261. }
  2262.  
  2263. static int
  2264. is_constant_false(c, n)
  2265.     struct compiling *c;
  2266.     node *n;
  2267. {
  2268.     PyObject *v;
  2269.     int i;
  2270.  
  2271.   /* Label to avoid tail recursion */
  2272.   next:
  2273.     switch (TYPE(n)) {
  2274.  
  2275.     case suite:
  2276.         if (NCH(n) == 1) {
  2277.             n = CHILD(n, 0);
  2278.             goto next;
  2279.         }
  2280.         /* Fall through */
  2281.     case file_input:
  2282.         for (i = 0; i < NCH(n); i++) {
  2283.             node *ch = CHILD(n, i);
  2284.             if (TYPE(ch) == stmt) {
  2285.                 n = ch;
  2286.                 goto next;
  2287.             }
  2288.         }
  2289.         break;
  2290.  
  2291.     case stmt:
  2292.     case simple_stmt:
  2293.     case small_stmt:
  2294.         n = CHILD(n, 0);
  2295.         goto next;
  2296.  
  2297.     case expr_stmt:
  2298.     case testlist:
  2299.     case test:
  2300.     case and_test:
  2301.     case not_test:
  2302.     case comparison:
  2303.     case expr:
  2304.     case xor_expr:
  2305.     case and_expr:
  2306.     case shift_expr:
  2307.     case arith_expr:
  2308.     case term:
  2309.     case factor:
  2310.     case power:
  2311.     case atom:
  2312.         if (NCH(n) == 1) {
  2313.             n = CHILD(n, 0);
  2314.             goto next;
  2315.         }
  2316.         break;
  2317.  
  2318.     case NAME:
  2319.         if (Py_OptimizeFlag && strcmp(STR(n), "__debug__") == 0)
  2320.             return 1;
  2321.         break;
  2322.  
  2323.     case NUMBER:
  2324.         v = parsenumber(c, STR(n));
  2325.         if (v == NULL) {
  2326.             PyErr_Clear();
  2327.             break;
  2328.         }
  2329.         i = PyObject_IsTrue(v);
  2330.         Py_DECREF(v);
  2331.         return i == 0;
  2332.  
  2333.     case STRING:
  2334.         v = parsestr(STR(n));
  2335.         if (v == NULL) {
  2336.             PyErr_Clear();
  2337.             break;
  2338.         }
  2339.         i = PyObject_IsTrue(v);
  2340.         Py_DECREF(v);
  2341.         return i == 0;
  2342.  
  2343.     }
  2344.     return 0;
  2345. }
  2346.  
  2347. static void
  2348. com_if_stmt(c, n)
  2349.     struct compiling *c;
  2350.     node *n;
  2351. {
  2352.     int i;
  2353.     int anchor = 0;
  2354.     REQ(n, if_stmt);
  2355.     /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
  2356.     for (i = 0; i+3 < NCH(n); i+=4) {
  2357.         int a = 0;
  2358.         node *ch = CHILD(n, i+1);
  2359.         if (is_constant_false(c, ch))
  2360.             continue;
  2361.         if (i > 0)
  2362.             com_addoparg(c, SET_LINENO, ch->n_lineno);
  2363.         com_node(c, ch);
  2364.         com_addfwref(c, JUMP_IF_FALSE, &a);
  2365.         com_addbyte(c, POP_TOP);
  2366.         com_pop(c, 1);
  2367.         com_node(c, CHILD(n, i+3));
  2368.         com_addfwref(c, JUMP_FORWARD, &anchor);
  2369.         com_backpatch(c, a);
  2370.         /* We jump here with an extra entry which we now pop */
  2371.         com_addbyte(c, POP_TOP);
  2372.     }
  2373.     if (i+2 < NCH(n))
  2374.         com_node(c, CHILD(n, i+2));
  2375.     if (anchor)
  2376.         com_backpatch(c, anchor);
  2377. }
  2378.  
  2379. static void
  2380. com_while_stmt(c, n)
  2381.     struct compiling *c;
  2382.     node *n;
  2383. {
  2384.     int break_anchor = 0;
  2385.     int anchor = 0;
  2386.     int save_begin = c->c_begin;
  2387.     REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
  2388.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2389.     block_push(c, SETUP_LOOP);
  2390.     c->c_begin = c->c_nexti;
  2391.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2392.     com_node(c, CHILD(n, 1));
  2393.     com_addfwref(c, JUMP_IF_FALSE, &anchor);
  2394.     com_addbyte(c, POP_TOP);
  2395.     com_pop(c, 1);
  2396.     c->c_loops++;
  2397.     com_node(c, CHILD(n, 3));
  2398.     c->c_loops--;
  2399.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2400.     c->c_begin = save_begin;
  2401.     com_backpatch(c, anchor);
  2402.     /* We jump here with one entry more on the stack */
  2403.     com_addbyte(c, POP_TOP);
  2404.     com_addbyte(c, POP_BLOCK);
  2405.     block_pop(c, SETUP_LOOP);
  2406.     if (NCH(n) > 4)
  2407.         com_node(c, CHILD(n, 6));
  2408.     com_backpatch(c, break_anchor);
  2409. }
  2410.  
  2411. static void
  2412. com_for_stmt(c, n)
  2413.     struct compiling *c;
  2414.     node *n;
  2415. {
  2416.     PyObject *v;
  2417.     int break_anchor = 0;
  2418.     int anchor = 0;
  2419.     int save_begin = c->c_begin;
  2420.     REQ(n, for_stmt);
  2421.     /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
  2422.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2423.     block_push(c, SETUP_LOOP);
  2424.     com_node(c, CHILD(n, 3));
  2425.     v = PyInt_FromLong(0L);
  2426.     if (v == NULL)
  2427.         c->c_errors++;
  2428.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  2429.     com_push(c, 1);
  2430.     Py_XDECREF(v);
  2431.     c->c_begin = c->c_nexti;
  2432.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2433.     com_addfwref(c, FOR_LOOP, &anchor);
  2434.     com_push(c, 1);
  2435.     com_assign(c, CHILD(n, 1), OP_ASSIGN);
  2436.     c->c_loops++;
  2437.     com_node(c, CHILD(n, 5));
  2438.     c->c_loops--;
  2439.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2440.     c->c_begin = save_begin;
  2441.     com_backpatch(c, anchor);
  2442.     com_pop(c, 2); /* FOR_LOOP has popped these */
  2443.     com_addbyte(c, POP_BLOCK);
  2444.     block_pop(c, SETUP_LOOP);
  2445.     if (NCH(n) > 8)
  2446.         com_node(c, CHILD(n, 8));
  2447.     com_backpatch(c, break_anchor);
  2448. }
  2449.  
  2450. /* Code generated for "try: S finally: Sf" is as follows:
  2451.    
  2452.         SETUP_FINALLY    L
  2453.         <code for S>
  2454.         POP_BLOCK
  2455.         LOAD_CONST    <nil>
  2456.     L:    <code for Sf>
  2457.         END_FINALLY
  2458.    
  2459.    The special instructions use the block stack.  Each block
  2460.    stack entry contains the instruction that created it (here
  2461.    SETUP_FINALLY), the level of the value stack at the time the
  2462.    block stack entry was created, and a label (here L).
  2463.    
  2464.    SETUP_FINALLY:
  2465.     Pushes the current value stack level and the label
  2466.     onto the block stack.
  2467.    POP_BLOCK:
  2468.     Pops en entry from the block stack, and pops the value
  2469.     stack until its level is the same as indicated on the
  2470.     block stack.  (The label is ignored.)
  2471.    END_FINALLY:
  2472.     Pops a variable number of entries from the *value* stack
  2473.     and re-raises the exception they specify.  The number of
  2474.     entries popped depends on the (pseudo) exception type.
  2475.    
  2476.    The block stack is unwound when an exception is raised:
  2477.    when a SETUP_FINALLY entry is found, the exception is pushed
  2478.    onto the value stack (and the exception condition is cleared),
  2479.    and the interpreter jumps to the label gotten from the block
  2480.    stack.
  2481.    
  2482.    Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  2483.    (The contents of the value stack is shown in [], with the top
  2484.    at the right; 'tb' is trace-back info, 'val' the exception's
  2485.    associated value, and 'exc' the exception.)
  2486.    
  2487.    Value stack        Label    Instruction    Argument
  2488.    []                SETUP_EXCEPT    L1
  2489.    []                <code for S>
  2490.    []                POP_BLOCK
  2491.    []                JUMP_FORWARD    L0
  2492.    
  2493.    [tb, val, exc]    L1:    DUP                )
  2494.    [tb, val, exc, exc]        <evaluate E1>            )
  2495.    [tb, val, exc, exc, E1]    COMPARE_OP    EXC_MATCH    ) only if E1
  2496.    [tb, val, exc, 1-or-0]    JUMP_IF_FALSE    L2        )
  2497.    [tb, val, exc, 1]        POP                )
  2498.    [tb, val, exc]        POP
  2499.    [tb, val]            <assign to V1>    (or POP if no V1)
  2500.    [tb]                POP
  2501.    []                <code for S1>
  2502.                    JUMP_FORWARD    L0
  2503.    
  2504.    [tb, val, exc, 0]    L2:    POP
  2505.    [tb, val, exc]        DUP
  2506.    .............................etc.......................
  2507.  
  2508.    [tb, val, exc, 0]    Ln+1:    POP
  2509.    [tb, val, exc]           END_FINALLY    # re-raise exception
  2510.    
  2511.    []            L0:    <next statement>
  2512.    
  2513.    Of course, parts are not generated if Vi or Ei is not present.
  2514. */
  2515.  
  2516. static void
  2517. com_try_except(c, n)
  2518.     struct compiling *c;
  2519.     node *n;
  2520. {
  2521.     int except_anchor = 0;
  2522.     int end_anchor = 0;
  2523.     int else_anchor = 0;
  2524.     int i;
  2525.     node *ch;
  2526.  
  2527.     com_addfwref(c, SETUP_EXCEPT, &except_anchor);
  2528.     block_push(c, SETUP_EXCEPT);
  2529.     com_node(c, CHILD(n, 2));
  2530.     com_addbyte(c, POP_BLOCK);
  2531.     block_pop(c, SETUP_EXCEPT);
  2532.     com_addfwref(c, JUMP_FORWARD, &else_anchor);
  2533.     com_backpatch(c, except_anchor);
  2534.     for (i = 3;
  2535.          i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
  2536.          i += 3) {
  2537.         /* except_clause: 'except' [expr [',' var]] */
  2538.         if (except_anchor == 0) {
  2539.             com_error(c, PyExc_SyntaxError,
  2540.                   "default 'except:' must be last");
  2541.             break;
  2542.         }
  2543.         except_anchor = 0;
  2544.         com_push(c, 3); /* tb, val, exc pushed by exception */
  2545.         com_addoparg(c, SET_LINENO, ch->n_lineno);
  2546.         if (NCH(ch) > 1) {
  2547.             com_addbyte(c, DUP_TOP);
  2548.             com_push(c, 1);
  2549.             com_node(c, CHILD(ch, 1));
  2550.             com_addoparg(c, COMPARE_OP, EXC_MATCH);
  2551.             com_pop(c, 1);
  2552.             com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
  2553.             com_addbyte(c, POP_TOP);
  2554.             com_pop(c, 1);
  2555.         }
  2556.         com_addbyte(c, POP_TOP);
  2557.         com_pop(c, 1);
  2558.         if (NCH(ch) > 3)
  2559.             com_assign(c, CHILD(ch, 3), OP_ASSIGN);
  2560.         else {
  2561.             com_addbyte(c, POP_TOP);
  2562.             com_pop(c, 1);
  2563.         }
  2564.         com_addbyte(c, POP_TOP);
  2565.         com_pop(c, 1);
  2566.         com_node(c, CHILD(n, i+2));
  2567.         com_addfwref(c, JUMP_FORWARD, &end_anchor);
  2568.         if (except_anchor) {
  2569.             com_backpatch(c, except_anchor);
  2570.             /* We come in with [tb, val, exc, 0] on the
  2571.                stack; one pop and it's the same as
  2572.                expected at the start of the loop */
  2573.             com_addbyte(c, POP_TOP);
  2574.         }
  2575.     }
  2576.     /* We actually come in here with [tb, val, exc] but the
  2577.        END_FINALLY will zap those and jump around.
  2578.        The c_stacklevel does not reflect them so we need not pop
  2579.        anything. */
  2580.     com_addbyte(c, END_FINALLY);
  2581.     com_backpatch(c, else_anchor);
  2582.     if (i < NCH(n))
  2583.         com_node(c, CHILD(n, i+2));
  2584.     com_backpatch(c, end_anchor);
  2585. }
  2586.  
  2587. static void
  2588. com_try_finally(c, n)
  2589.     struct compiling *c;
  2590.     node *n;
  2591. {
  2592.     int finally_anchor = 0;
  2593.     node *ch;
  2594.  
  2595.     com_addfwref(c, SETUP_FINALLY, &finally_anchor);
  2596.     block_push(c, SETUP_FINALLY);
  2597.     com_node(c, CHILD(n, 2));
  2598.     com_addbyte(c, POP_BLOCK);
  2599.     block_pop(c, SETUP_FINALLY);
  2600.     block_push(c, END_FINALLY);
  2601.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2602.     /* While the generated code pushes only one item,
  2603.        the try-finally handling can enter here with
  2604.        up to three items.  OK, here are the details:
  2605.        3 for an exception, 2 for RETURN, 1 for BREAK. */
  2606.     com_push(c, 3);
  2607.     com_backpatch(c, finally_anchor);
  2608.     ch = CHILD(n, NCH(n)-1);
  2609.     com_addoparg(c, SET_LINENO, ch->n_lineno);
  2610.     com_node(c, ch);
  2611.     com_addbyte(c, END_FINALLY);
  2612.     block_pop(c, END_FINALLY);
  2613.     com_pop(c, 3); /* Matches the com_push above */
  2614. }
  2615.  
  2616. static void
  2617. com_try_stmt(c, n)
  2618.     struct compiling *c;
  2619.     node *n;
  2620. {
  2621.     REQ(n, try_stmt);
  2622.     /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  2623.      | 'try' ':' suite 'finally' ':' suite */
  2624.     if (TYPE(CHILD(n, 3)) != except_clause)
  2625.         com_try_finally(c, n);
  2626.     else
  2627.         com_try_except(c, n);
  2628. }
  2629.  
  2630. static node *
  2631. get_rawdocstring(n)
  2632.     node *n;
  2633. {
  2634.     int i;
  2635.  
  2636.   /* Label to avoid tail recursion */
  2637.   next:
  2638.     switch (TYPE(n)) {
  2639.  
  2640.     case suite:
  2641.         if (NCH(n) == 1) {
  2642.             n = CHILD(n, 0);
  2643.             goto next;
  2644.         }
  2645.         /* Fall through */
  2646.     case file_input:
  2647.         for (i = 0; i < NCH(n); i++) {
  2648.             node *ch = CHILD(n, i);
  2649.             if (TYPE(ch) == stmt) {
  2650.                 n = ch;
  2651.                 goto next;
  2652.             }
  2653.         }
  2654.         break;
  2655.  
  2656.     case stmt:
  2657.     case simple_stmt:
  2658.     case small_stmt:
  2659.         n = CHILD(n, 0);
  2660.         goto next;
  2661.  
  2662.     case expr_stmt:
  2663.     case testlist:
  2664.     case test:
  2665.     case and_test:
  2666.     case not_test:
  2667.     case comparison:
  2668.     case expr:
  2669.     case xor_expr:
  2670.     case and_expr:
  2671.     case shift_expr:
  2672.     case arith_expr:
  2673.     case term:
  2674.     case factor:
  2675.     case power:
  2676.         if (NCH(n) == 1) {
  2677.             n = CHILD(n, 0);
  2678.             goto next;
  2679.         }
  2680.         break;
  2681.  
  2682.     case atom:
  2683.         if (TYPE(CHILD(n, 0)) == STRING)
  2684.             return n;
  2685.         break;
  2686.  
  2687.     }
  2688.     return NULL;
  2689. }
  2690.  
  2691. static PyObject *
  2692. get_docstring(n)
  2693.     node *n;
  2694. {
  2695.     /* Don't generate doc-strings if run with -OO */
  2696.     if (Py_OptimizeFlag > 1)
  2697.         return NULL;
  2698.     n = get_rawdocstring(n);
  2699.     if (n == NULL)
  2700.         return NULL;
  2701.     return parsestrplus(n);
  2702. }
  2703.  
  2704. static void
  2705. com_suite(c, n)
  2706.     struct compiling *c;
  2707.     node *n;
  2708. {
  2709.     REQ(n, suite);
  2710.     /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
  2711.     if (NCH(n) == 1) {
  2712.         com_node(c, CHILD(n, 0));
  2713.     }
  2714.     else {
  2715.         int i;
  2716.         for (i = 0; i < NCH(n); i++) {
  2717.             node *ch = CHILD(n, i);
  2718.             if (TYPE(ch) == stmt)
  2719.                 com_node(c, ch);
  2720.         }
  2721.     }
  2722. }
  2723.  
  2724. /* ARGSUSED */
  2725. static void
  2726. com_continue_stmt(c, n)
  2727.     struct compiling *c;
  2728.     node *n; /* Not used, but passed for consistency */
  2729. {
  2730.     int i = c->c_nblocks;
  2731.     if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
  2732.         com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2733.     }
  2734.     else {
  2735.         com_error(c, PyExc_SyntaxError,
  2736.               "'continue' not properly in loop");
  2737.     }
  2738.     /* XXX Could allow it inside a 'finally' clause
  2739.        XXX if we could pop the exception still on the stack */
  2740. }
  2741.  
  2742. static int
  2743. com_argdefs(c, n)
  2744.     struct compiling *c;
  2745.     node *n;
  2746. {
  2747.     int i, nch, nargs, ndefs;
  2748.     if (TYPE(n) == lambdef) {
  2749.         /* lambdef: 'lambda' [varargslist] ':' test */
  2750.         n = CHILD(n, 1);
  2751.     }
  2752.     else {
  2753.         REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */
  2754.         n = CHILD(n, 2);
  2755.         REQ(n, parameters); /* parameters: '(' [varargslist] ')' */
  2756.         n = CHILD(n, 1);
  2757.     }
  2758.     if (TYPE(n) != varargslist)
  2759.             return 0;
  2760.     /* varargslist:
  2761.         (fpdef ['=' test] ',')* '*' ....... |
  2762.         fpdef ['=' test] (',' fpdef ['=' test])* [','] */
  2763.     nch = NCH(n);
  2764.     nargs = 0;
  2765.     ndefs = 0;
  2766.     for (i = 0; i < nch; i++) {
  2767.         int t;
  2768.         if (TYPE(CHILD(n, i)) == STAR ||
  2769.             TYPE(CHILD(n, i)) == DOUBLESTAR)
  2770.             break;
  2771.         nargs++;
  2772.         i++;
  2773.         if (i >= nch)
  2774.             t = RPAR; /* Anything except EQUAL or COMMA */
  2775.         else
  2776.             t = TYPE(CHILD(n, i));
  2777.         if (t == EQUAL) {
  2778.             i++;
  2779.             ndefs++;
  2780.             com_node(c, CHILD(n, i));
  2781.             i++;
  2782.             if (i >= nch)
  2783.                 break;
  2784.             t = TYPE(CHILD(n, i));
  2785.         }
  2786.         else {
  2787.             /* Treat "(a=1, b)" as an error */
  2788.             if (ndefs)
  2789.                 com_error(c, PyExc_SyntaxError,
  2790.                 "non-default argument follows default argument");
  2791.         }
  2792.         if (t != COMMA)
  2793.             break;
  2794.     }
  2795.     return ndefs;
  2796. }
  2797.  
  2798. static void
  2799. com_funcdef(c, n)
  2800.     struct compiling *c;
  2801.     node *n;
  2802. {
  2803.     PyObject *v;
  2804.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2805.     v = (PyObject *)icompile(n, c);
  2806.     if (v == NULL)
  2807.         c->c_errors++;
  2808.     else {
  2809.         int i = com_addconst(c, v);
  2810.         int ndefs = com_argdefs(c, n);
  2811.         com_addoparg(c, LOAD_CONST, i);
  2812.         com_push(c, 1);
  2813.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  2814.         com_pop(c, ndefs);
  2815.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2816.         com_pop(c, 1);
  2817.         Py_DECREF(v);
  2818.     }
  2819. }
  2820.  
  2821. static void
  2822. com_bases(c, n)
  2823.     struct compiling *c;
  2824.     node *n;
  2825. {
  2826.     int i;
  2827.     REQ(n, testlist);
  2828.     /* testlist: test (',' test)* [','] */
  2829.     for (i = 0; i < NCH(n); i += 2)
  2830.         com_node(c, CHILD(n, i));
  2831.     i = (NCH(n)+1) / 2;
  2832.     com_addoparg(c, BUILD_TUPLE, i);
  2833.     com_pop(c, i-1);
  2834. }
  2835.  
  2836. static void
  2837. com_classdef(c, n)
  2838.     struct compiling *c;
  2839.     node *n;
  2840. {
  2841.     int i;
  2842.     PyObject *v;
  2843.     REQ(n, classdef);
  2844.     /* classdef: class NAME ['(' testlist ')'] ':' suite */
  2845.     if ((v = PyString_InternFromString(STR(CHILD(n, 1)))) == NULL) {
  2846.         c->c_errors++;
  2847.         return;
  2848.     }
  2849.     /* Push the class name on the stack */
  2850.     i = com_addconst(c, v);
  2851.     com_addoparg(c, LOAD_CONST, i);
  2852.     com_push(c, 1);
  2853.     Py_DECREF(v);
  2854.     /* Push the tuple of base classes on the stack */
  2855.     if (TYPE(CHILD(n, 2)) != LPAR) {
  2856.         com_addoparg(c, BUILD_TUPLE, 0);
  2857.         com_push(c, 1);
  2858.     }
  2859.     else
  2860.         com_bases(c, CHILD(n, 3));
  2861.     v = (PyObject *)icompile(n, c);
  2862.     if (v == NULL)
  2863.         c->c_errors++;
  2864.     else {
  2865.         i = com_addconst(c, v);
  2866.         com_addoparg(c, LOAD_CONST, i);
  2867.         com_push(c, 1);
  2868.         com_addoparg(c, MAKE_FUNCTION, 0);
  2869.         com_addoparg(c, CALL_FUNCTION, 0);
  2870.         com_addbyte(c, BUILD_CLASS);
  2871.         com_pop(c, 2);
  2872.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2873.         Py_DECREF(v);
  2874.     }
  2875. }
  2876.  
  2877. static void
  2878. com_node(c, n)
  2879.     struct compiling *c;
  2880.     node *n;
  2881. {
  2882.     switch (TYPE(n)) {
  2883.     
  2884.     /* Definition nodes */
  2885.     
  2886.     case funcdef:
  2887.         com_funcdef(c, n);
  2888.         break;
  2889.     case classdef:
  2890.         com_classdef(c, n);
  2891.         break;
  2892.     
  2893.     /* Trivial parse tree nodes */
  2894.     
  2895.     case stmt:
  2896.     case small_stmt:
  2897.     case flow_stmt:
  2898.         com_node(c, CHILD(n, 0));
  2899.         break;
  2900.  
  2901.     case simple_stmt:
  2902.         /* small_stmt (';' small_stmt)* [';'] NEWLINE */
  2903.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2904.         {
  2905.             int i;
  2906.             for (i = 0; i < NCH(n)-1; i += 2)
  2907.                 com_node(c, CHILD(n, i));
  2908.         }
  2909.         break;
  2910.     
  2911.     case compound_stmt:
  2912.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2913.         com_node(c, CHILD(n, 0));
  2914.         break;
  2915.  
  2916.     /* Statement nodes */
  2917.     
  2918.     case expr_stmt:
  2919.         com_expr_stmt(c, n);
  2920.         break;
  2921.     case print_stmt:
  2922.         com_print_stmt(c, n);
  2923.         break;
  2924.     case del_stmt: /* 'del' exprlist */
  2925.         com_assign(c, CHILD(n, 1), OP_DELETE);
  2926.         break;
  2927.     case pass_stmt:
  2928.         break;
  2929.     case break_stmt:
  2930.         if (c->c_loops == 0) {
  2931.             com_error(c, PyExc_SyntaxError,
  2932.                   "'break' outside loop");
  2933.         }
  2934.         com_addbyte(c, BREAK_LOOP);
  2935.         break;
  2936.     case continue_stmt:
  2937.         com_continue_stmt(c, n);
  2938.         break;
  2939.     case return_stmt:
  2940.         com_return_stmt(c, n);
  2941.         break;
  2942.     case raise_stmt:
  2943.         com_raise_stmt(c, n);
  2944.         break;
  2945.     case import_stmt:
  2946.         com_import_stmt(c, n);
  2947.         break;
  2948.     case global_stmt:
  2949.         com_global_stmt(c, n);
  2950.         break;
  2951.     case exec_stmt:
  2952.         com_exec_stmt(c, n);
  2953.         break;
  2954.     case assert_stmt:
  2955.         com_assert_stmt(c, n);
  2956.         break;
  2957.     case if_stmt:
  2958.         com_if_stmt(c, n);
  2959.         break;
  2960.     case while_stmt:
  2961.         com_while_stmt(c, n);
  2962.         break;
  2963.     case for_stmt:
  2964.         com_for_stmt(c, n);
  2965.         break;
  2966.     case try_stmt:
  2967.         com_try_stmt(c, n);
  2968.         break;
  2969.     case suite:
  2970.         com_suite(c, n);
  2971.         break;
  2972.     
  2973.     /* Expression nodes */
  2974.     
  2975.     case testlist:
  2976.         com_list(c, n, 0);
  2977.         break;
  2978.     case test:
  2979.         com_test(c, n);
  2980.         break;
  2981.     case and_test:
  2982.         com_and_test(c, n);
  2983.         break;
  2984.     case not_test:
  2985.         com_not_test(c, n);
  2986.         break;
  2987.     case comparison:
  2988.         com_comparison(c, n);
  2989.         break;
  2990.     case exprlist:
  2991.         com_list(c, n, 0);
  2992.         break;
  2993.     case expr:
  2994.         com_expr(c, n);
  2995.         break;
  2996.     case xor_expr:
  2997.         com_xor_expr(c, n);
  2998.         break;
  2999.     case and_expr:
  3000.         com_and_expr(c, n);
  3001.         break;
  3002.     case shift_expr:
  3003.         com_shift_expr(c, n);
  3004.         break;
  3005.     case arith_expr:
  3006.         com_arith_expr(c, n);
  3007.         break;
  3008.     case term:
  3009.         com_term(c, n);
  3010.         break;
  3011.     case factor:
  3012.         com_factor(c, n);
  3013.         break;
  3014.     case power:
  3015.         com_power(c, n);
  3016.         break;
  3017.     case atom:
  3018.         com_atom(c, n);
  3019.         break;
  3020.     
  3021.     default:
  3022.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  3023.         com_error(c, PyExc_SystemError,
  3024.               "com_node: unexpected node type");
  3025.     }
  3026. }
  3027.  
  3028. static void com_fplist Py_PROTO((struct compiling *, node *));
  3029.  
  3030. static void
  3031. com_fpdef(c, n)
  3032.     struct compiling *c;
  3033.     node *n;
  3034. {
  3035.     REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3036.     if (TYPE(CHILD(n, 0)) == LPAR)
  3037.         com_fplist(c, CHILD(n, 1));
  3038.     else {
  3039.         com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0))));
  3040.         com_pop(c, 1);
  3041.     }
  3042. }
  3043.  
  3044. static void
  3045. com_fplist(c, n)
  3046.     struct compiling *c;
  3047.     node *n;
  3048. {
  3049.     REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
  3050.     if (NCH(n) == 1) {
  3051.         com_fpdef(c, CHILD(n, 0));
  3052.     }
  3053.     else {
  3054.         int i = (NCH(n)+1)/2;
  3055.         com_addoparg(c, UNPACK_TUPLE, i);
  3056.         com_push(c, i-1);
  3057.         for (i = 0; i < NCH(n); i += 2)
  3058.             com_fpdef(c, CHILD(n, i));
  3059.     }
  3060. }
  3061.  
  3062. static void
  3063. com_arglist(c, n)
  3064.     struct compiling *c;
  3065.     node *n;
  3066. {
  3067.     int nch, i;
  3068.     int complex = 0;
  3069.     char nbuf[10];
  3070.     REQ(n, varargslist);
  3071.     /* varargslist:
  3072.         (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
  3073.     nch = NCH(n);
  3074.     /* Enter all arguments in table of locals */
  3075.     for (i = 0; i < nch; i++) {
  3076.         node *ch = CHILD(n, i);
  3077.         node *fp;
  3078.         char *name;
  3079.         if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3080.             break;
  3081.         REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3082.         fp = CHILD(ch, 0);
  3083.         if (TYPE(fp) == NAME)
  3084.             name = STR(fp);
  3085.         else {
  3086.             name = nbuf;
  3087.             sprintf(nbuf, ".%d", i);
  3088.             complex = 1;
  3089.         }
  3090.         com_newlocal(c, name);
  3091.         c->c_argcount++;
  3092.         if (++i >= nch)
  3093.             break;
  3094.         ch = CHILD(n, i);
  3095.         if (TYPE(ch) == EQUAL)
  3096.             i += 2;
  3097.         else
  3098.             REQ(ch, COMMA);
  3099.     }
  3100.     /* Handle *arguments */
  3101.     if (i < nch) {
  3102.         node *ch;
  3103.         ch = CHILD(n, i);
  3104.         if (TYPE(ch) != DOUBLESTAR) {
  3105.             REQ(ch, STAR);
  3106.             ch = CHILD(n, i+1);
  3107.             if (TYPE(ch) == NAME) {
  3108.                 c->c_flags |= CO_VARARGS;
  3109.                 i += 3;
  3110.                 com_newlocal(c, STR(ch));
  3111.             }
  3112.         }
  3113.     }
  3114.     /* Handle **keywords */
  3115.     if (i < nch) {
  3116.         node *ch;
  3117.         ch = CHILD(n, i);
  3118.         if (TYPE(ch) != DOUBLESTAR) {
  3119.             REQ(ch, STAR);
  3120.             ch = CHILD(n, i+1);
  3121.             REQ(ch, STAR);
  3122.             ch = CHILD(n, i+2);
  3123.         }
  3124.         else
  3125.             ch = CHILD(n, i+1);
  3126.         REQ(ch, NAME);
  3127.         c->c_flags |= CO_VARKEYWORDS;
  3128.         com_newlocal(c, STR(ch));
  3129.     }
  3130.     if (complex) {
  3131.         /* Generate code for complex arguments only after
  3132.            having counted the simple arguments */
  3133.         int ilocal = 0;
  3134.         for (i = 0; i < nch; i++) {
  3135.             node *ch = CHILD(n, i);
  3136.             node *fp;
  3137.             if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3138.                 break;
  3139.             REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3140.             fp = CHILD(ch, 0);
  3141.             if (TYPE(fp) != NAME) {
  3142.                 com_addoparg(c, LOAD_FAST, ilocal);
  3143.                 com_push(c, 1);
  3144.                 com_fpdef(c, ch);
  3145.             }
  3146.             ilocal++;
  3147.             if (++i >= nch)
  3148.                 break;
  3149.             ch = CHILD(n, i);
  3150.             if (TYPE(ch) == EQUAL)
  3151.                 i += 2;
  3152.             else
  3153.                 REQ(ch, COMMA);
  3154.         }
  3155.     }
  3156. }
  3157.  
  3158. static void
  3159. com_file_input(c, n)
  3160.     struct compiling *c;
  3161.     node *n;
  3162. {
  3163.     int i;
  3164.     PyObject *doc;
  3165.     REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
  3166.     doc = get_docstring(n);
  3167.     if (doc != NULL) {
  3168.         int i = com_addconst(c, doc);
  3169.         Py_DECREF(doc);
  3170.         com_addoparg(c, LOAD_CONST, i);
  3171.         com_push(c, 1);
  3172.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3173.         com_pop(c, 1);
  3174.     }
  3175.     for (i = 0; i < NCH(n); i++) {
  3176.         node *ch = CHILD(n, i);
  3177.         if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
  3178.             com_node(c, ch);
  3179.     }
  3180. }
  3181.  
  3182. /* Top-level compile-node interface */
  3183.  
  3184. static void
  3185. compile_funcdef(c, n)
  3186.     struct compiling *c;
  3187.     node *n;
  3188. {
  3189.     PyObject *doc;
  3190.     node *ch;
  3191.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  3192.     c->c_name = STR(CHILD(n, 1));
  3193.     doc = get_docstring(CHILD(n, 4));
  3194.     if (doc != NULL) {
  3195.         (void) com_addconst(c, doc);
  3196.         Py_DECREF(doc);
  3197.     }
  3198.     else
  3199.         (void) com_addconst(c, Py_None); /* No docstring */
  3200.     ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
  3201.     ch = CHILD(ch, 1); /* ')' | varargslist */
  3202.     if (TYPE(ch) == varargslist)
  3203.         com_arglist(c, ch);
  3204.     c->c_infunction = 1;
  3205.     com_node(c, CHILD(n, 4));
  3206.     c->c_infunction = 0;
  3207.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3208.     com_push(c, 1);
  3209.     com_addbyte(c, RETURN_VALUE);
  3210.     com_pop(c, 1);
  3211. }
  3212.  
  3213. static void
  3214. compile_lambdef(c, n)
  3215.     struct compiling *c;
  3216.     node *n;
  3217. {
  3218.     node *ch;
  3219.     REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */
  3220.     c->c_name = "<lambda>";
  3221.  
  3222.     ch = CHILD(n, 1);
  3223.     (void) com_addconst(c, Py_None); /* No docstring */
  3224.     if (TYPE(ch) == varargslist) {
  3225.         com_arglist(c, ch);
  3226.         ch = CHILD(n, 3);
  3227.     }
  3228.     else
  3229.         ch = CHILD(n, 2);
  3230.     com_node(c, ch);
  3231.     com_addbyte(c, RETURN_VALUE);
  3232.     com_pop(c, 1);
  3233. }
  3234.  
  3235. static void
  3236. compile_classdef(c, n)
  3237.     struct compiling *c;
  3238.     node *n;
  3239. {
  3240.     node *ch;
  3241.     PyObject *doc;
  3242.     REQ(n, classdef);
  3243.     /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
  3244.     c->c_name = STR(CHILD(n, 1));
  3245. #ifdef PRIVATE_NAME_MANGLING
  3246.     c->c_private = c->c_name;
  3247. #endif
  3248.     ch = CHILD(n, NCH(n)-1); /* The suite */
  3249.     doc = get_docstring(ch);
  3250.     if (doc != NULL) {
  3251.         int i = com_addconst(c, doc);
  3252.         Py_DECREF(doc);
  3253.         com_addoparg(c, LOAD_CONST, i);
  3254.         com_push(c, 1);
  3255.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3256.         com_pop(c, 1);
  3257.     }
  3258.     else
  3259.         (void) com_addconst(c, Py_None);
  3260.     com_node(c, ch);
  3261.     com_addbyte(c, LOAD_LOCALS);
  3262.     com_push(c, 1);
  3263.     com_addbyte(c, RETURN_VALUE);
  3264.     com_pop(c, 1);
  3265. }
  3266.  
  3267. static void
  3268. compile_node(c, n)
  3269.     struct compiling *c;
  3270.     node *n;
  3271. {
  3272.     com_addoparg(c, SET_LINENO, n->n_lineno);
  3273.     
  3274.     switch (TYPE(n)) {
  3275.     
  3276.     case single_input: /* One interactive command */
  3277.         /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
  3278.         c->c_interactive++;
  3279.         n = CHILD(n, 0);
  3280.         if (TYPE(n) != NEWLINE)
  3281.             com_node(c, n);
  3282.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3283.         com_push(c, 1);
  3284.         com_addbyte(c, RETURN_VALUE);
  3285.         com_pop(c, 1);
  3286.         c->c_interactive--;
  3287.         break;
  3288.     
  3289.     case file_input: /* A whole file, or built-in function exec() */
  3290.         com_file_input(c, n);
  3291.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3292.         com_push(c, 1);
  3293.         com_addbyte(c, RETURN_VALUE);
  3294.         com_pop(c, 1);
  3295.         break;
  3296.     
  3297.     case eval_input: /* Built-in function input() */
  3298.         com_node(c, CHILD(n, 0));
  3299.         com_addbyte(c, RETURN_VALUE);
  3300.         com_pop(c, 1);
  3301.         break;
  3302.     
  3303.     case lambdef: /* anonymous function definition */
  3304.         compile_lambdef(c, n);
  3305.         break;
  3306.  
  3307.     case funcdef: /* A function definition */
  3308.         compile_funcdef(c, n);
  3309.         break;
  3310.     
  3311.     case classdef: /* A class definition */
  3312.         compile_classdef(c, n);
  3313.         break;
  3314.     
  3315.     default:
  3316.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  3317.         com_error(c, PyExc_SystemError,
  3318.               "compile_node: unexpected node type");
  3319.     }
  3320. }
  3321.  
  3322. /* Optimization for local variables in functions (and *only* functions).
  3323.  
  3324.    This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
  3325.    instructions that refer to local variables with LOAD_FAST etc.
  3326.    The latter instructions are much faster because they don't need to
  3327.    look up the variable name in a dictionary.
  3328.  
  3329.    To find all local variables, we check all STORE_NAME, IMPORT_FROM
  3330.    and DELETE_NAME instructions.  This yields all local variables,
  3331.    function definitions, class definitions and import statements.
  3332.    Argument names have already been entered into the list by the
  3333.    special processing for the argument list.
  3334.  
  3335.    All remaining LOAD_NAME instructions must refer to non-local (global
  3336.    or builtin) variables, so are replaced by LOAD_GLOBAL.
  3337.  
  3338.    There are two problems:  'from foo import *' and 'exec' may introduce
  3339.    local variables that we can't know while compiling.  If this is the
  3340.    case, we can still optimize bona fide locals (since those
  3341.    statements will be surrounded by fast_2_locals() and
  3342.    locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
  3343.  
  3344.    NB: this modifies the string object c->c_code!  */
  3345.  
  3346. static void
  3347. optimize(c)
  3348.     struct compiling *c;
  3349. {
  3350.     unsigned char *next_instr, *cur_instr;
  3351.     int opcode;
  3352.     int oparg = 0;
  3353.     PyObject *name;
  3354.     PyObject *error_type, *error_value, *error_traceback;
  3355.     
  3356. #define NEXTOP()    (*next_instr++)
  3357. #define NEXTARG()    (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
  3358. #define GETITEM(v, i)    (PyList_GetItem((v), (i)))
  3359. #define GETNAMEOBJ(i)    (GETITEM(c->c_names, (i)))
  3360.     
  3361.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  3362.  
  3363.     c->c_flags |= CO_OPTIMIZED;
  3364.     
  3365.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3366.     for (;;) {
  3367.         opcode = NEXTOP();
  3368.         if (opcode == STOP_CODE)
  3369.             break;
  3370.         if (HAS_ARG(opcode))
  3371.             oparg = NEXTARG();
  3372.         switch (opcode) {
  3373.         case STORE_NAME:
  3374.         case DELETE_NAME:
  3375.         case IMPORT_FROM:
  3376.             com_addlocal_o(c, GETNAMEOBJ(oparg));
  3377.             break;
  3378.         case EXEC_STMT:
  3379.             c->c_flags &= ~CO_OPTIMIZED;
  3380.             break;
  3381.         }
  3382.     }
  3383.     
  3384.     if (PyDict_GetItemString(c->c_locals, "*") != NULL)
  3385.         c->c_flags &= ~CO_OPTIMIZED;
  3386.     
  3387.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3388.     for (;;) {
  3389.         cur_instr = next_instr;
  3390.         opcode = NEXTOP();
  3391.         if (opcode == STOP_CODE)
  3392.             break;
  3393.         if (HAS_ARG(opcode))
  3394.             oparg = NEXTARG();
  3395.         if (opcode == LOAD_NAME ||
  3396.             opcode == STORE_NAME ||
  3397.             opcode == DELETE_NAME) {
  3398.             PyObject *v;
  3399.             int i;
  3400.             name = GETNAMEOBJ(oparg);
  3401.             v = PyDict_GetItem(c->c_locals, name);
  3402.             if (v == NULL) {
  3403.                 if (opcode == LOAD_NAME &&
  3404.                     (c->c_flags&CO_OPTIMIZED))
  3405.                     cur_instr[0] = LOAD_GLOBAL;
  3406.                 continue;
  3407.             }
  3408.             i = PyInt_AsLong(v);
  3409.             switch (opcode) {
  3410.             case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
  3411.             case STORE_NAME: cur_instr[0] = STORE_FAST; break;
  3412.             case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
  3413.             }
  3414.             cur_instr[1] = i & 0xff;
  3415.             cur_instr[2] = (i>>8) & 0xff;
  3416.         }
  3417.     }
  3418.  
  3419.     if (c->c_errors == 0)
  3420.         PyErr_Restore(error_type, error_value, error_traceback);
  3421. }
  3422.  
  3423. PyCodeObject *
  3424. PyNode_Compile(n, filename)
  3425.     node *n;
  3426.     char *filename;
  3427. {
  3428.     return jcompile(n, filename, NULL);
  3429. }
  3430.  
  3431. static PyCodeObject *
  3432. icompile(n, base)
  3433.     node *n;
  3434.     struct compiling *base;
  3435. {
  3436.     return jcompile(n, base->c_filename, base);
  3437. }
  3438.  
  3439. static PyCodeObject *
  3440. jcompile(n, filename, base)
  3441.     node *n;
  3442.     char *filename;
  3443.     struct compiling *base;
  3444. {
  3445.     struct compiling sc;
  3446.     PyCodeObject *co;
  3447.     if (!com_init(&sc, filename))
  3448.         return NULL;
  3449. #ifdef PRIVATE_NAME_MANGLING
  3450.     if (base)
  3451.         sc.c_private = base->c_private;
  3452.     else
  3453.         sc.c_private = NULL;
  3454. #endif
  3455.     compile_node(&sc, n);
  3456.     com_done(&sc);
  3457.     if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) {
  3458.         optimize(&sc);
  3459.         sc.c_flags |= CO_NEWLOCALS;
  3460.     }
  3461.     else if (TYPE(n) == classdef)
  3462.         sc.c_flags |= CO_NEWLOCALS;
  3463.     co = NULL;
  3464.     if (sc.c_errors == 0) {
  3465.         PyObject *consts, *names, *varnames, *filename, *name;
  3466.         consts = PyList_AsTuple(sc.c_consts);
  3467.         names = PyList_AsTuple(sc.c_names);
  3468.         varnames = PyList_AsTuple(sc.c_varnames);
  3469.         filename = PyString_InternFromString(sc.c_filename);
  3470.         name = PyString_InternFromString(sc.c_name);
  3471.         if (!PyErr_Occurred())
  3472.             co = PyCode_New(sc.c_argcount,
  3473.                        sc.c_nlocals,
  3474.                        sc.c_maxstacklevel,
  3475.                        sc.c_flags,
  3476.                        sc.c_code,
  3477.                        consts,
  3478.                        names,
  3479.                        varnames,
  3480.                        filename,
  3481.                        name,
  3482.                        sc.c_firstlineno,
  3483.                        sc.c_lnotab);
  3484.         Py_XDECREF(consts);
  3485.         Py_XDECREF(names);
  3486.         Py_XDECREF(varnames);
  3487.         Py_XDECREF(filename);
  3488.         Py_XDECREF(name);
  3489.     }
  3490.     else if (!PyErr_Occurred()) {
  3491.         /* This could happen if someone called PyErr_Clear() after an
  3492.            error was reported above.  That's not supposed to happen,
  3493.            but I just plugged one case and I'm not sure there can't be
  3494.            others.  In that case, raise SystemError so that at least
  3495.            it gets reported instead dumping core. */
  3496.         PyErr_SetString(PyExc_SystemError, "lost syntax error");
  3497.     }
  3498.     com_free(&sc);
  3499.     return co;
  3500. }
  3501.  
  3502. int
  3503. PyCode_Addr2Line(co, addrq)
  3504.     PyCodeObject *co;
  3505.     int addrq;
  3506. {
  3507.     int size = PyString_Size(co->co_lnotab) / 2;
  3508.     unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
  3509.     int line = co->co_firstlineno;
  3510.     int addr = 0;
  3511.     while (--size >= 0) {
  3512.         addr += *p++;
  3513.         if (addr > addrq)
  3514.             break;
  3515.         line += *p++;
  3516.     }
  3517.     return line;
  3518. }
  3519.